<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.13.2"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CAD_Doc: Advanced googletest Topics</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<script type="text/javascript" src="clipboard.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="cookie.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
  $(function() { init_search(); });
/* @license-end */
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr id="projectrow">
  <td id="projectalign">
   <div id="projectname">CAD_Doc<span id="projectnumber">&#160;1.0</span>
   </div>
   <div id="projectbrief">cad synopsis</div>
  </td>
    <td>        <div id="MSearchBox" class="MSearchBoxInactive">
        <span class="left">
          <span id="MSearchSelect"                onmouseover="return searchBox.OnSearchSelectShow()"                onmouseout="return searchBox.OnSearchSelectHide()">&#160;</span>
          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)" 
               onblur="searchBox.OnSearchFieldFocus(false)" 
               onkeyup="searchBox.OnSearchFieldChange(event)"/>
          </span><span class="right">
            <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.svg" alt=""/></a>
          </span>
        </div>
</td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.13.2 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
var searchBox = new SearchBox("searchBox", "search/",'.html');
/* @license-end */
</script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
$(function() { codefold.init(0); });
/* @license-end */
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
      <div id="nav-sync" class="sync"></div>
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
$(function(){initNavTree('md__build_2__deps_2googletest-src_2docs_2advanced.html',''); initResizable(true); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<div id="MSearchResults">
<div class="SRPage">
<div id="SRIndex">
<div id="SRResults"></div>
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
</div>
</div>
</div>
</div>

<div><div class="header">
  <div class="headertitle"><div class="title">Advanced googletest Topics</div></div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><a class="anchor" id="autotoc_md10"></a></p>
<h1><a class="anchor" id="autotoc_md11"></a>
Introduction</h1>
<p>Now that you have read the <a class="el" href="md__build_2__deps_2googletest-src_2docs_2primer.html">googletest Primer</a> and learned how to write tests using googletest, it's time to learn some new tricks. This document will show you more assertions as well as how to construct complex failure messages, propagate fatal failures, reuse and speed up your test fixtures, and use various flags with your tests.</p>
<h1><a class="anchor" id="autotoc_md12"></a>
More Assertions</h1>
<p>This section covers some less frequently used, but still significant, assertions.</p>
<h2><a class="anchor" id="autotoc_md13"></a>
Explicit Success and Failure</h2>
<p>See <a href="reference/assertions.md#success-failure">Explicit Success and Failure</a> in the Assertions Reference.</p>
<h2><a class="anchor" id="autotoc_md14"></a>
Exception Assertions</h2>
<p>See <a href="reference/assertions.md#exceptions">Exception Assertions</a> in the Assertions Reference.</p>
<h2><a class="anchor" id="autotoc_md15"></a>
Predicate Assertions for Better Error Messages</h2>
<p>Even though googletest has a rich set of assertions, they can never be complete, as it's impossible (nor a good idea) to anticipate all scenarios a user might run into. Therefore, sometimes a user has to use <code>EXPECT_TRUE()</code> to check a complex expression, for lack of a better macro. This has the problem of not showing you the values of the parts of the expression, making it hard to understand what went wrong. As a workaround, some users choose to construct the failure message by themselves, streaming it into <code>EXPECT_TRUE()</code>. However, this is awkward especially when the expression has side-effects or is expensive to evaluate.</p>
<p>googletest gives you three different options to solve this problem:</p>
<h3><a class="anchor" id="autotoc_md16"></a>
Using an Existing Boolean Function</h3>
<p>If you already have a function or functor that returns <code>bool</code> (or a type that can be implicitly converted to <code>bool</code>), you can use it in a <em>predicate assertion</em> to get the function arguments printed for free. See <a href="reference/assertions.md#EXPECT_PRED"><code>EXPECT_PRED*</code></a> in the Assertions Reference for details.</p>
<h3><a class="anchor" id="autotoc_md17"></a>
Using a Function That Returns an AssertionResult</h3>
<p>While <code>EXPECT_PRED*()</code> and friends are handy for a quick job, the syntax is not satisfactory: you have to use different macros for different arities, and it feels more like Lisp than C++. The <code>::testing::AssertionResult</code> class solves this problem.</p>
<p>An <code>AssertionResult</code> object represents the result of an assertion (whether it's a success or a failure, and an associated message). You can create an <code>AssertionResult</code> using one of these factory functions:</p>
<div class="fragment"><div class="line"><span class="keyword">namespace </span>testing {</div>
<div class="line"> </div>
<div class="line"><span class="comment">// Returns an AssertionResult object to indicate that an assertion has</span></div>
<div class="line"><span class="comment">// succeeded.</span></div>
<div class="line">AssertionResult AssertionSuccess();</div>
<div class="line"> </div>
<div class="line"><span class="comment">// Returns an AssertionResult object to indicate that an assertion has</span></div>
<div class="line"><span class="comment">// failed.</span></div>
<div class="line">AssertionResult AssertionFailure();</div>
<div class="line"> </div>
<div class="line">}</div>
</div><!-- fragment --><p>You can then use the <code>&lt;&lt;</code> operator to stream messages to the <code>AssertionResult</code> object.</p>
<p>To provide more readable messages in Boolean assertions (e.g. <code>EXPECT_TRUE()</code>), write a predicate function that returns <code>AssertionResult</code> instead of <code>bool</code>. For example, if you define <code>IsEven()</code> as:</p>
<div class="fragment"><div class="line">testing::AssertionResult IsEven(<span class="keywordtype">int</span> n) {</div>
<div class="line">  <span class="keywordflow">if</span> ((n % 2) == 0)</div>
<div class="line">    <span class="keywordflow">return</span> testing::AssertionSuccess();</div>
<div class="line">  <span class="keywordflow">else</span></div>
<div class="line">    <span class="keywordflow">return</span> testing::AssertionFailure() &lt;&lt; n &lt;&lt; <span class="stringliteral">&quot; is odd&quot;</span>;</div>
<div class="line">}</div>
</div><!-- fragment --><p>instead of:</p>
<div class="fragment"><div class="line"><span class="keywordtype">bool</span> IsEven(<span class="keywordtype">int</span> n) {</div>
<div class="line">  <span class="keywordflow">return</span> (n % 2) == 0;</div>
<div class="line">}</div>
</div><!-- fragment --><p>the failed assertion <code>EXPECT_TRUE(IsEven(Fib(4)))</code> will print:</p>
<div class="fragment"><div class="line">Value of: IsEven(Fib(4))</div>
<div class="line">  Actual: false (3 is odd)</div>
<div class="line">Expected: true</div>
</div><!-- fragment --><p>instead of a more opaque</p>
<div class="fragment"><div class="line">Value of: IsEven(Fib(4))</div>
<div class="line">  Actual: false</div>
<div class="line">Expected: true</div>
</div><!-- fragment --><p>If you want informative messages in <code>EXPECT_FALSE</code> and <code>ASSERT_FALSE</code> as well (one third of Boolean assertions in the Google code base are negative ones), and are fine with making the predicate slower in the success case, you can supply a success message:</p>
<div class="fragment"><div class="line">testing::AssertionResult IsEven(<span class="keywordtype">int</span> n) {</div>
<div class="line">  <span class="keywordflow">if</span> ((n % 2) == 0)</div>
<div class="line">    <span class="keywordflow">return</span> testing::AssertionSuccess() &lt;&lt; n &lt;&lt; <span class="stringliteral">&quot; is even&quot;</span>;</div>
<div class="line">  <span class="keywordflow">else</span></div>
<div class="line">    <span class="keywordflow">return</span> testing::AssertionFailure() &lt;&lt; n &lt;&lt; <span class="stringliteral">&quot; is odd&quot;</span>;</div>
<div class="line">}</div>
</div><!-- fragment --><p>Then the statement <code>EXPECT_FALSE(IsEven(Fib(6)))</code> will print</p>
<div class="fragment"><div class="line">Value of: IsEven(Fib(6))</div>
<div class="line">   Actual: true (8 is even)</div>
<div class="line">Expected: false</div>
</div><!-- fragment --><h3><a class="anchor" id="autotoc_md18"></a>
Using a Predicate-Formatter</h3>
<p>If you find the default message generated by <a href="reference/assertions.md#EXPECT_PRED"><code>EXPECT_PRED*</code></a> and <a href="reference/assertions.md#EXPECT_TRUE"><code>EXPECT_TRUE</code></a> unsatisfactory, or some arguments to your predicate do not support streaming to <code>ostream</code>, you can instead use <em>predicate-formatter assertions</em> to <em>fully</em> customize how the message is formatted. See <a href="reference/assertions.md#EXPECT_PRED_FORMAT"><code>EXPECT_PRED_FORMAT*</code></a> in the Assertions Reference for details.</p>
<h2><a class="anchor" id="autotoc_md19"></a>
Floating-Point Comparison</h2>
<p>See <a href="reference/assertions.md#floating-point">Floating-Point Comparison</a> in the Assertions Reference.</p>
<h3><a class="anchor" id="autotoc_md20"></a>
Floating-Point Predicate-Format Functions</h3>
<p>Some floating-point operations are useful, but not that often used. In order to avoid an explosion of new macros, we provide them as predicate-format functions that can be used in the predicate assertion macro <a href="reference/assertions.md#EXPECT_PRED_FORMAT"><code>EXPECT_PRED_FORMAT2</code></a>, for example:</p>
<div class="fragment"><div class="line"><span class="keyword">using </span>::testing::FloatLE;</div>
<div class="line"><span class="keyword">using </span>::testing::DoubleLE;</div>
<div class="line">...</div>
<div class="line">EXPECT_PRED_FORMAT2(FloatLE, val1, val2);</div>
<div class="line">EXPECT_PRED_FORMAT2(DoubleLE, val1, val2);</div>
</div><!-- fragment --><p>The above code verifies that <code>val1</code> is less than, or approximately equal to, <code>val2</code>.</p>
<h2><a class="anchor" id="autotoc_md21"></a>
Asserting Using gMock Matchers</h2>
<p>See <a href="reference/assertions.md#EXPECT_THAT"><code>EXPECT_THAT</code></a> in the Assertions Reference.</p>
<h2><a class="anchor" id="autotoc_md22"></a>
More String Assertions</h2>
<p>(Please read the previous section first if you haven't.)</p>
<p>You can use the gMock <a href="reference/matchers.md#string-matchers">string matchers</a> with <a href="reference/assertions.md#EXPECT_THAT"><code>EXPECT_THAT</code></a> to do more string comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For example,</p>
<div class="fragment"><div class="line"><span class="keyword">using </span>::testing::HasSubstr;</div>
<div class="line"><span class="keyword">using </span>::testing::MatchesRegex;</div>
<div class="line">...</div>
<div class="line">  ASSERT_THAT(foo_string, HasSubstr(<span class="stringliteral">&quot;needle&quot;</span>));</div>
<div class="line">  EXPECT_THAT(bar_string, MatchesRegex(<span class="stringliteral">&quot;\\w*\\d+&quot;</span>));</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md23"></a>
Windows HRESULT assertions</h2>
<p>See <a href="reference/assertions.md#HRESULT">Windows HRESULT Assertions</a> in the Assertions Reference.</p>
<h2><a class="anchor" id="autotoc_md24"></a>
Type Assertions</h2>
<p>You can call the function</p>
<div class="fragment"><div class="line">::testing::StaticAssertTypeEq&lt;T1, T2&gt;();</div>
</div><!-- fragment --><p>to assert that types <code>T1</code> and <code>T2</code> are the same. The function does nothing if the assertion is satisfied. If the types are different, the function call will fail to compile, the compiler error message will say that <code>T1 and T2 are not the same type</code> and most likely (depending on the compiler) show you the actual values of <code>T1</code> and <code>T2</code>. This is mainly useful inside template code.</p>
<p><b>Caveat</b>: When used inside a member function of a class template or a function template, <code>StaticAssertTypeEq&lt;T1, T2&gt;()</code> is effective only if the function is instantiated. For example, given:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">class </span>Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keywordtype">void</span> Bar() { testing::StaticAssertTypeEq&lt;int, T&gt;(); }</div>
<div class="line">};</div>
</div><!-- fragment --><p>the code:</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> Test1() { Foo&lt;bool&gt; foo; }</div>
</div><!-- fragment --><p>will not generate a compiler error, as <code>Foo&lt;bool&gt;::Bar()</code> is never actually instantiated. Instead, you need:</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> Test2() { Foo&lt;bool&gt; foo; foo.Bar(); }</div>
</div><!-- fragment --><p>to cause a compiler error.</p>
<h2><a class="anchor" id="autotoc_md25"></a>
Assertion Placement</h2>
<p>You can use assertions in any C++ function. In particular, it doesn't have to be a method of the test fixture class. The one constraint is that assertions that generate a fatal failure (<code>FAIL*</code> and <code>ASSERT_*</code>) can only be used in void-returning functions. This is a consequence of Google's not using exceptions. By placing it in a non-void function you'll get a confusing compile error like <code>"error: void value not ignored as it ought to be"</code> or &lsquo;"cannot
initialize return object of type 'bool&amp;rsquo; with an rvalue of type 'void'"` or `"error: no viable conversion from 'void' to 'string'"`.</p>
<p>If you need to use fatal assertions in a function that returns non-void, one option is to make the function return the value in an out parameter instead. For example, you can rewrite <code>T2 Foo(T1 x)</code> to <code>void Foo(T1 x, T2* result)</code>. You need to make sure that <code>*result</code> contains some sensible value even when the function returns prematurely. As the function now returns <code>void</code>, you can use any assertion inside of it.</p>
<p>If changing the function's type is not an option, you should just use assertions that generate non-fatal failures, such as <code>ADD_FAILURE*</code> and <code>EXPECT_*</code>.</p>
<p>{: .callout .note} NOTE: Constructors and destructors are not considered void-returning functions, according to the C++ language specification, and so you may not use fatal assertions in them; you'll get a compilation error if you try. Instead, either call <code>abort</code> and crash the entire test executable, or put the fatal assertion in a <code>SetUp</code>/<code>TearDown</code> function; see <a href="faq.md#CtorVsSetUp">constructor/destructor vs. <code>SetUp</code>/<code>TearDown</code></a></p>
<p>{: .callout .warning} WARNING: A fatal assertion in a helper function (private void-returning method) called from a constructor or destructor does not terminate the current test, as your intuition might suggest: it merely returns from the constructor or destructor early, possibly leaving your object in a partially-constructed or partially-destructed state! You almost certainly want to <code>abort</code> or use <code>SetUp</code>/<code>TearDown</code> instead.</p>
<h1><a class="anchor" id="autotoc_md26"></a>
Skipping test execution</h1>
<p>Related to the assertions <code>SUCCEED()</code> and <code>FAIL()</code>, you can prevent further test execution at runtime with the <code>GTEST_SKIP()</code> macro. This is useful when you need to check for preconditions of the system under test during runtime and skip tests in a meaningful way.</p>
<p><code>GTEST_SKIP()</code> can be used in individual test cases or in the <code>SetUp()</code> methods of classes derived from either <code><a class="el" href="classtesting_1_1_environment.html">testing::Environment</a></code> or <code><a class="el" href="classtesting_1_1_test.html">testing::Test</a></code>. For example:</p>
<div class="fragment"><div class="line">TEST(SkipTest, DoesSkip) {</div>
<div class="line">  GTEST_SKIP() &lt;&lt; <span class="stringliteral">&quot;Skipping single test&quot;</span>;</div>
<div class="line">  EXPECT_EQ(0, 1);  <span class="comment">// Won&#39;t fail; it won&#39;t be executed</span></div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>SkipFixture : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test.html">::testing::Test</a> {</div>
<div class="line"> <span class="keyword">protected</span>:</div>
<div class="line">  <span class="keywordtype">void</span> SetUp()<span class="keyword"> override </span>{</div>
<div class="line">    GTEST_SKIP() &lt;&lt; <span class="stringliteral">&quot;Skipping all tests for this fixture&quot;</span>;</div>
<div class="line">  }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="comment">// Tests for SkipFixture won&#39;t be executed.</span></div>
<div class="line">TEST_F(SkipFixture, SkipsOneTest) {</div>
<div class="line">  EXPECT_EQ(5, 7);  <span class="comment">// Won&#39;t fail</span></div>
<div class="line">}</div>
<div class="ttc" id="aclasstesting_1_1_test_html"><div class="ttname"><a href="classtesting_1_1_test.html">testing::Test</a></div><div class="ttdef"><b>Definition</b> gtest.h:242</div></div>
</div><!-- fragment --><p>As with assertion macros, you can stream a custom message into <code>GTEST_SKIP()</code>.</p>
<h1><a class="anchor" id="autotoc_md27"></a>
Teaching googletest How to Print Your Values</h1>
<p>When a test assertion such as <code>EXPECT_EQ</code> fails, googletest prints the argument values to help you debug. It does this using a user-extensible value printer.</p>
<p>This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the <code>&lt;&lt;</code> operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out.</p>
<p>As mentioned earlier, the printer is <em>extensible</em>. That means you can teach it to do a better job at printing your particular type than to dump the bytes. To do that, define <code>&lt;&lt;</code> for your type:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &lt;ostream&gt;</span></div>
<div class="line"> </div>
<div class="line"><span class="keyword">namespace </span>foo {</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>Bar {  <span class="comment">// We want googletest to be able to print instances of this.</span></div>
<div class="line">...</div>
<div class="line">  <span class="comment">// Create a free inline friend function.</span></div>
<div class="line">  <span class="keyword">friend</span> std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, <span class="keyword">const</span> Bar&amp; bar) {</div>
<div class="line">    <span class="keywordflow">return</span> os &lt;&lt; bar.DebugString();  <span class="comment">// whatever needed to print bar to os</span></div>
<div class="line">  }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="comment">// If you can&#39;t declare the function in the class it&#39;s important that the</span></div>
<div class="line"><span class="comment">// &lt;&lt; operator is defined in the SAME namespace that defines Bar.  C++&#39;s look-up</span></div>
<div class="line"><span class="comment">// rules rely on that.</span></div>
<div class="line">std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, <span class="keyword">const</span> Bar&amp; bar) {</div>
<div class="line">  <span class="keywordflow">return</span> os &lt;&lt; bar.DebugString();  <span class="comment">// whatever needed to print bar to os</span></div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">}  <span class="comment">// namespace foo</span></div>
</div><!-- fragment --><p>Sometimes, this might not be an option: your team may consider it bad style to have a <code>&lt;&lt;</code> operator for <code>Bar</code>, or <code>Bar</code> may already have a <code>&lt;&lt;</code> operator that doesn't do what you want (and you cannot change it). If so, you can instead define a <code>PrintTo()</code> function like this:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &lt;ostream&gt;</span></div>
<div class="line"> </div>
<div class="line"><span class="keyword">namespace </span>foo {</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>Bar {</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">friend</span> <span class="keywordtype">void</span> PrintTo(<span class="keyword">const</span> Bar&amp; bar, std::ostream* os) {</div>
<div class="line">    *os &lt;&lt; bar.DebugString();  <span class="comment">// whatever needed to print bar to os</span></div>
<div class="line">  }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="comment">// If you can&#39;t declare the function in the class it&#39;s important that PrintTo()</span></div>
<div class="line"><span class="comment">// is defined in the SAME namespace that defines Bar.  C++&#39;s look-up rules rely</span></div>
<div class="line"><span class="comment">// on that.</span></div>
<div class="line"><span class="keywordtype">void</span> PrintTo(<span class="keyword">const</span> Bar&amp; bar, std::ostream* os) {</div>
<div class="line">  *os &lt;&lt; bar.DebugString();  <span class="comment">// whatever needed to print bar to os</span></div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">}  <span class="comment">// namespace foo</span></div>
</div><!-- fragment --><p>If you have defined both <code>&lt;&lt;</code> and <code>PrintTo()</code>, the latter will be used when googletest is concerned. This allows you to customize how the value appears in googletest's output without affecting code that relies on the behavior of its <code>&lt;&lt;</code> operator.</p>
<p>If you want to print a value <code>x</code> using googletest's value printer yourself, just call <code>::testing::PrintToString(x)</code>, which returns an <code>std::string</code>:</p>
<div class="fragment"><div class="line"><a class="code hl_class" href="classvector.html">vector&lt;pair&lt;Bar, int&gt;</a> &gt; bar_ints = GetBarIntVector();</div>
<div class="line"> </div>
<div class="line">EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))</div>
<div class="line">    &lt;&lt; <span class="stringliteral">&quot;bar_ints = &quot;</span> &lt;&lt; testing::PrintToString(bar_ints);</div>
<div class="ttc" id="aclassvector_html"><div class="ttname"><a href="classvector.html">vector</a></div></div>
</div><!-- fragment --><h1><a class="anchor" id="autotoc_md28"></a>
Death Tests</h1>
<p>In many applications, there are assertions that can cause application failure if a condition is not met. These consistency checks, which ensure that the program is in a known good state, are there to fail at the earliest possible time after some program state is corrupted. If the assertion checks the wrong condition, then the program may proceed in an erroneous state, which could lead to memory corruption, security holes, or worse. Hence it is vitally important to test that such assertion statements work as expected.</p>
<p>Since these precondition checks cause the processes to die, we call such tests <em>death tests</em>. More generally, any test that checks that a program terminates (except by throwing an exception) in an expected fashion is also a death test.</p>
<p>Note that if a piece of code throws an exception, we don't consider it "death" for the purpose of death tests, as the caller of the code could catch the exception and avoid the crash. If you want to verify exceptions thrown by your code, see Exception Assertions.</p>
<p>If you want to test <code>EXPECT_*()/ASSERT_*()</code> failures in your test code, see &quot;Catching&quot; Failures.</p>
<h2><a class="anchor" id="autotoc_md29"></a>
How to Write a Death Test</h2>
<p>GoogleTest provides assertion macros to support death tests. See <a href="reference/assertions.md#death">Death Assertions</a> in the Assertions Reference for details.</p>
<p>To write a death test, simply use one of the macros inside your test function. For example,</p>
<div class="fragment"><div class="line">TEST(MyDeathTest, Foo) {</div>
<div class="line">  <span class="comment">// This death test uses a compound statement.</span></div>
<div class="line">  ASSERT_DEATH({</div>
<div class="line">    <span class="keywordtype">int</span> n = 5;</div>
<div class="line">    Foo(&amp;n);</div>
<div class="line">  }, <span class="stringliteral">&quot;Error on line .* of Foo()&quot;</span>);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TEST(MyDeathTest, NormalExit) {</div>
<div class="line">  EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), <span class="stringliteral">&quot;Success&quot;</span>);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TEST(MyDeathTest, KillProcess) {</div>
<div class="line">  EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL),</div>
<div class="line">              <span class="stringliteral">&quot;Sending myself unblockable signal&quot;</span>);</div>
<div class="line">}</div>
</div><!-- fragment --><p>verifies that:</p>
<ul>
<li>calling <code>Foo(5)</code> causes the process to die with the given error message,</li>
<li>calling <code>NormalExit()</code> causes the process to print <code>"Success"</code> to stderr and exit with exit code 0, and</li>
<li>calling <code>KillProcess()</code> kills the process with signal <code>SIGKILL</code>.</li>
</ul>
<p>The test function body may contain other assertions and statements as well, if necessary.</p>
<p>Note that a death test only cares about three things:</p>
<ol type="1">
<li>does <code>statement</code> abort or exit the process?</li>
<li>(in the case of <code>ASSERT_EXIT</code> and <code>EXPECT_EXIT</code>) does the exit status satisfy <code>predicate</code>? Or (in the case of <code>ASSERT_DEATH</code> and <code>EXPECT_DEATH</code>) is the exit status non-zero? And</li>
<li>does the stderr output match <code>matcher</code>?</li>
</ol>
<p>In particular, if <code>statement</code> generates an <code>ASSERT_*</code> or <code>EXPECT_*</code> failure, it will <b>not</b> cause the death test to fail, as googletest assertions don't abort the process.</p>
<h2><a class="anchor" id="autotoc_md30"></a>
Death Test Naming</h2>
<p>{: .callout .important} IMPORTANT: We strongly recommend you to follow the convention of naming your <b>test suite</b> (not test) <code>*DeathTest</code> when it contains a death test, as demonstrated in the above example. The Death Tests And Threads section below explains why.</p>
<p>If a test fixture class is shared by normal tests and death tests, you can use <code>using</code> or <code>typedef</code> to introduce an alias for the fixture class and avoid duplicating its code:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>FooTest : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test.html">testing::Test</a> { ... };</div>
<div class="line"> </div>
<div class="line"><span class="keyword">using </span>FooDeathTest = FooTest;</div>
<div class="line"> </div>
<div class="line">TEST_F(FooTest, DoesThis) {</div>
<div class="line">  <span class="comment">// normal test</span></div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TEST_F(FooDeathTest, DoesThat) {</div>
<div class="line">  <span class="comment">// death test</span></div>
<div class="line">}</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md31"></a>
Regular Expression Syntax</h2>
<p>When built with Bazel and using Abseil, googletest uses the <a href="https://github.com/google/re2/wiki/Syntax">RE2</a> syntax. Otherwise, for POSIX systems (Linux, Cygwin, Mac), googletest uses the <a href="http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04">POSIX extended regular expression</a> syntax. To learn about POSIX syntax, you may want to read this <a href="http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended">Wikipedia entry</a>.</p>
<p>On Windows, googletest uses its own simple regular expression implementation. It lacks many features. For example, we don't support union (<code>"x|y"</code>), grouping (<code>"(xy)"</code>), brackets (<code>"[xy]"</code>), and repetition count (<code>"x{5,7}"</code>), among others. Below is what we do support (<code>A</code> denotes a literal character, period (<code>.</code>), or a single <code>\\</code> escape sequence; <code>x</code> and <code>y</code> denote regular expressions.):</p>
<table class="markdownTable">
<tr class="markdownTableHead">
<th class="markdownTableHeadNone">Expression   </th><th class="markdownTableHeadNone">Meaning    </th></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>c</code>   </td><td class="markdownTableBodyNone">matches any literal character <code>c</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>\\d</code>   </td><td class="markdownTableBodyNone">matches any decimal digit    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>\\D</code>   </td><td class="markdownTableBodyNone">matches any character that's not a decimal digit    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>\\f</code>   </td><td class="markdownTableBodyNone">matches <code>\f</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>\\n</code>   </td><td class="markdownTableBodyNone">matches <code>\n</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>\\r</code>   </td><td class="markdownTableBodyNone">matches <code>\r</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>\\s</code>   </td><td class="markdownTableBodyNone">matches any ASCII whitespace, including <code>\n</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>\\S</code>   </td><td class="markdownTableBodyNone">matches any character that's not a whitespace    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>\\t</code>   </td><td class="markdownTableBodyNone">matches <code>\t</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>\\v</code>   </td><td class="markdownTableBodyNone">matches <code>\v</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>\\w</code>   </td><td class="markdownTableBodyNone">matches any letter, <code>_</code>, or decimal digit    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>\\W</code>   </td><td class="markdownTableBodyNone">matches any character that <code>\\w</code> doesn't match    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>\\c</code>   </td><td class="markdownTableBodyNone">matches any literal character <code>c</code>, which must be a punctuation    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>.</code>   </td><td class="markdownTableBodyNone">matches any single character except <code>\n</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>A?</code>   </td><td class="markdownTableBodyNone">matches 0 or 1 occurrences of <code>A</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>A*</code>   </td><td class="markdownTableBodyNone">matches 0 or many occurrences of <code>A</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>A+</code>   </td><td class="markdownTableBodyNone">matches 1 or many occurrences of <code>A</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>^</code>   </td><td class="markdownTableBodyNone">matches the beginning of a string (not that of each line)    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>$</code>   </td><td class="markdownTableBodyNone">matches the end of a string (not that of each line)    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>xy</code>   </td><td class="markdownTableBodyNone">matches <code>x</code> followed by <code>y</code>   </td></tr>
</table>
<p>To help you determine which capability is available on your system, googletest defines macros to govern which regular expression it is using. The macros are: <code>GTEST_USES_SIMPLE_RE=1</code> or <code>GTEST_USES_POSIX_RE=1</code>. If you want your death tests to work in all cases, you can either <code>#if</code> on these macros or use the more limited syntax only.</p>
<h2><a class="anchor" id="autotoc_md32"></a>
How It Works</h2>
<p>See <a href="reference/assertions.md#death">Death Assertions</a> in the Assertions Reference.</p>
<h2><a class="anchor" id="autotoc_md33"></a>
Death Tests And Threads</h2>
<p>The reason for the two death test styles has to do with thread safety. Due to well-known problems with forking in the presence of threads, death tests should be run in a single-threaded context. Sometimes, however, it isn't feasible to arrange that kind of environment. For example, statically-initialized modules may start threads before main is ever reached. Once threads have been created, it may be difficult or impossible to clean them up.</p>
<p>googletest has three features intended to raise awareness of threading issues.</p>
<ol type="1">
<li>A warning is emitted if multiple threads are running when a death test is encountered.</li>
<li>Test suites with a name ending in "DeathTest" are run before all other tests.</li>
<li>It uses <code>clone()</code> instead of <code>fork()</code> to spawn the child process on Linux (<code>clone()</code> is not available on Cygwin and Mac), as <code>fork()</code> is more likely to cause the child to hang when the parent process has multiple threads.</li>
</ol>
<p>It's perfectly fine to create threads inside a death test statement; they are executed in a separate process and cannot affect the parent.</p>
<h2><a class="anchor" id="autotoc_md34"></a>
Death Test Styles</h2>
<p>The "threadsafe" death test style was introduced in order to help mitigate the risks of testing in a possibly multithreaded environment. It trades increased test execution time (potentially dramatically so) for improved thread safety.</p>
<p>The automated testing framework does not set the style flag. You can choose a particular style of death tests by setting the flag programmatically:</p>
<div class="fragment"><div class="line">GTEST_FLAG_SET(death_test_style, <span class="stringliteral">&quot;threadsafe&quot;</span>)</div>
</div><!-- fragment --><p>You can do this in <code>main()</code> to set the style for all death tests in the binary, or in individual tests. Recall that flags are saved before running each test and restored afterwards, so you need not do that yourself. For example:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv) {</div>
<div class="line">  testing::InitGoogleTest(&amp;argc, argv);</div>
<div class="line">  GTEST_FLAG_SET(death_test_style, <span class="stringliteral">&quot;fast&quot;</span>);</div>
<div class="line">  <span class="keywordflow">return</span> RUN_ALL_TESTS();</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TEST(MyDeathTest, TestOne) {</div>
<div class="line">  GTEST_FLAG_SET(death_test_style, <span class="stringliteral">&quot;threadsafe&quot;</span>);</div>
<div class="line">  <span class="comment">// This test is run in the &quot;threadsafe&quot; style:</span></div>
<div class="line">  ASSERT_DEATH(ThisShouldDie(), <span class="stringliteral">&quot;&quot;</span>);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TEST(MyDeathTest, TestTwo) {</div>
<div class="line">  <span class="comment">// This test is run in the &quot;fast&quot; style:</span></div>
<div class="line">  ASSERT_DEATH(ThisShouldDie(), <span class="stringliteral">&quot;&quot;</span>);</div>
<div class="line">}</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md35"></a>
Caveats</h2>
<p>The <code>statement</code> argument of <code>ASSERT_EXIT()</code> can be any valid C++ statement. If it leaves the current function via a <code>return</code> statement or by throwing an exception, the death test is considered to have failed. Some googletest macros may return from the current function (e.g. <code>ASSERT_TRUE()</code>), so be sure to avoid them in <code>statement</code>.</p>
<p>Since <code>statement</code> runs in the child process, any in-memory side effect (e.g. modifying a variable, releasing memory, etc) it causes will <em>not</em> be observable in the parent process. In particular, if you release memory in a death test, your program will fail the heap check as the parent process will never see the memory reclaimed. To solve this problem, you can</p>
<ol type="1">
<li>try not to free memory in a death test;</li>
<li>free the memory again in the parent process; or</li>
<li>do not use the heap checker in your program.</li>
</ol>
<p>Due to an implementation detail, you cannot place multiple death test assertions on the same line; otherwise, compilation will fail with an unobvious error message.</p>
<p>Despite the improved thread safety afforded by the "threadsafe" style of death test, thread problems such as deadlock are still possible in the presence of handlers registered with <code>pthread_atfork(3)</code>.</p>
<h1><a class="anchor" id="autotoc_md36"></a>
Using Assertions in Sub-routines</h1>
<p>{: .callout .note} Note: If you want to put a series of test assertions in a subroutine to check for a complex condition, consider using <a href="gmock_cook_book.md#NewMatchers">a custom GMock matcher</a> instead. This lets you provide a more readable error message in case of failure and avoid all of the issues described below.</p>
<h2><a class="anchor" id="autotoc_md37"></a>
Adding Traces to Assertions</h2>
<p>If a test sub-routine is called from several places, when an assertion inside it fails, it can be hard to tell which invocation of the sub-routine the failure is from. You can alleviate this problem using extra logging or custom failure messages, but that usually clutters up your tests. A better solution is to use the <code>SCOPED_TRACE</code> macro or the <code>ScopedTrace</code> utility:</p>
<div class="fragment"><div class="line">SCOPED_TRACE(message);</div>
</div><!-- fragment --><div class="fragment"><div class="line">ScopedTrace trace(<span class="stringliteral">&quot;file_path&quot;</span>, line_number, message);</div>
</div><!-- fragment --><p>where <code>message</code> can be anything streamable to <code>std::ostream</code>. <code>SCOPED_TRACE</code> macro will cause the current file name, line number, and the given message to be added in every failure message. <code>ScopedTrace</code> accepts explicit file name and line number in arguments, which is useful for writing test helpers. The effect will be undone when the control leaves the current lexical scope.</p>
<p>For example,</p>
<div class="fragment"><div class="line">10: <span class="keywordtype">void</span> Sub1(<span class="keywordtype">int</span> n) {</div>
<div class="line">11:   EXPECT_EQ(Bar(n), 1);</div>
<div class="line">12:   EXPECT_EQ(Bar(n + 1), 2);</div>
<div class="line">13: }</div>
<div class="line">14:</div>
<div class="line">15: TEST(FooTest, Bar) {</div>
<div class="line">16:   {</div>
<div class="line">17:     SCOPED_TRACE(<span class="stringliteral">&quot;A&quot;</span>);  <span class="comment">// This trace point will be included in</span></div>
<div class="line">18:                         <span class="comment">// every failure in this scope.</span></div>
<div class="line">19:     Sub1(1);</div>
<div class="line">20:   }</div>
<div class="line">21:   <span class="comment">// Now it won&#39;t.</span></div>
<div class="line">22:   Sub1(9);</div>
<div class="line">23: }</div>
</div><!-- fragment --><p>could result in messages like these:</p>
<div class="fragment"><div class="line">path/to/foo_test.cc:11: Failure</div>
<div class="line">Value of: Bar(n)</div>
<div class="line">Expected: 1</div>
<div class="line">  Actual: 2</div>
<div class="line">Google Test trace:</div>
<div class="line">path/to/foo_test.cc:17: A</div>
<div class="line"> </div>
<div class="line">path/to/foo_test.cc:12: Failure</div>
<div class="line">Value of: Bar(n + 1)</div>
<div class="line">Expected: 2</div>
<div class="line">  Actual: 3</div>
</div><!-- fragment --><p>Without the trace, it would've been difficult to know which invocation of <code>Sub1()</code> the two failures come from respectively. (You could add an extra message to each assertion in <code>Sub1()</code> to indicate the value of <code>n</code>, but that's tedious.)</p>
<p>Some tips on using <code>SCOPED_TRACE</code>:</p>
<ol type="1">
<li>With a suitable message, it's often enough to use <code>SCOPED_TRACE</code> at the beginning of a sub-routine, instead of at each call site.</li>
<li>When calling sub-routines inside a loop, make the loop iterator part of the message in <code>SCOPED_TRACE</code> such that you can know which iteration the failure is from.</li>
<li>Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for <code>SCOPED_TRACE</code>. You can simply use <code>""</code>.</li>
<li>You can use <code>SCOPED_TRACE</code> in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered.</li>
<li>The trace dump is clickable in Emacs - hit <code>return</code> on a line number and you'll be taken to that line in the source file!</li>
</ol>
<h2><a class="anchor" id="autotoc_md38"></a>
Propagating Fatal Failures</h2>
<p>A common pitfall when using <code>ASSERT_*</code> and <code>FAIL*</code> is not understanding that when they fail they only abort the <em>current function</em>, not the entire test. For example, the following test will segfault:</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> Subroutine() {</div>
<div class="line">  <span class="comment">// Generates a fatal failure and aborts the current function.</span></div>
<div class="line">  ASSERT_EQ(1, 2);</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// The following won&#39;t be executed.</span></div>
<div class="line">  ...</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TEST(FooTest, Bar) {</div>
<div class="line">  Subroutine();  <span class="comment">// The intended behavior is for the fatal failure</span></div>
<div class="line">                 <span class="comment">// in Subroutine() to abort the entire test.</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// The actual behavior: the function goes on after Subroutine() returns.</span></div>
<div class="line">  <span class="keywordtype">int</span>* p = <span class="keyword">nullptr</span>;</div>
<div class="line">  *p = 3;  <span class="comment">// Segfault!</span></div>
<div class="line">}</div>
</div><!-- fragment --><p>To alleviate this, googletest provides three different solutions. You could use either exceptions, the <code>(ASSERT|EXPECT)_NO_FATAL_FAILURE</code> assertions or the <code>HasFatalFailure()</code> function. They are described in the following two subsections.</p>
<h3><a class="anchor" id="autotoc_md39"></a>
Asserting on Subroutines with an exception</h3>
<p>The following code can turn ASSERT-failure into an exception:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span><a class="code hl_class" href="class_throw_listener.html">ThrowListener</a> : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_empty_test_event_listener.html">testing::EmptyTestEventListener</a> {</div>
<div class="line">  <span class="keywordtype">void</span> OnTestPartResult(<span class="keyword">const</span> testing::TestPartResult&amp; result)<span class="keyword"> override </span>{</div>
<div class="line">    <span class="keywordflow">if</span> (result.type() == testing::TestPartResult::kFatalFailure) {</div>
<div class="line">      <span class="keywordflow">throw</span> testing::AssertionException(result);</div>
<div class="line">    }</div>
<div class="line">  }</div>
<div class="line">};</div>
<div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv) {</div>
<div class="line">  ...</div>
<div class="line">  testing::UnitTest::GetInstance()-&gt;listeners().Append(<span class="keyword">new</span> <a class="code hl_class" href="class_throw_listener.html">ThrowListener</a>);</div>
<div class="line">  <span class="keywordflow">return</span> RUN_ALL_TESTS();</div>
<div class="line">}</div>
<div class="ttc" id="aclass_throw_listener_html"><div class="ttname"><a href="class_throw_listener.html">ThrowListener</a></div><div class="ttdef"><b>Definition</b> gtest_assert_by_exception_test.cc:40</div></div>
<div class="ttc" id="aclasstesting_1_1_empty_test_event_listener_html"><div class="ttname"><a href="classtesting_1_1_empty_test_event_listener.html">testing::EmptyTestEventListener</a></div><div class="ttdef"><b>Definition</b> gtest.h:986</div></div>
</div><!-- fragment --><p>This listener should be added after other listeners if you have any, otherwise they won't see failed <code>OnTestPartResult</code>.</p>
<h3><a class="anchor" id="autotoc_md40"></a>
Asserting on Subroutines</h3>
<p>As shown above, if your test calls a subroutine that has an <code>ASSERT_*</code> failure in it, the test will continue after the subroutine returns. This may not be what you want.</p>
<p>Often people want fatal failures to propagate like exceptions. For that googletest offers the following macros:</p>
<table class="markdownTable">
<tr class="markdownTableHead">
<th class="markdownTableHeadNone">Fatal assertion   </th><th class="markdownTableHeadNone">Nonfatal assertion   </th><th class="markdownTableHeadNone">Verifies    </th></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>ASSERT_NO_FATAL_FAILURE(statement);</code>   </td><td class="markdownTableBodyNone"><code>EXPECT_NO_FATAL_FAILURE(statement);</code>   </td><td class="markdownTableBodyNone"><code>statement</code> doesn't generate any new fatal failures in the current thread.   </td></tr>
</table>
<p>Only failures in the thread that executes the assertion are checked to determine the result of this type of assertions. If <code>statement</code> creates new threads, failures in these threads are ignored.</p>
<p>Examples:</p>
<div class="fragment"><div class="line">ASSERT_NO_FATAL_FAILURE(Foo());</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">int</span> i;</div>
<div class="line">EXPECT_NO_FATAL_FAILURE({</div>
<div class="line">  i = Bar();</div>
<div class="line">});</div>
</div><!-- fragment --><p>Assertions from multiple threads are currently not supported on Windows.</p>
<h3><a class="anchor" id="autotoc_md41"></a>
Checking for Failures in the Current Test</h3>
<p><code>HasFatalFailure()</code> in the <code><a class="el" href="classtesting_1_1_test.html">testing::Test</a></code> class returns <code>true</code> if an assertion in the current test has suffered a fatal failure. This allows functions to catch fatal failures in a sub-routine and return early.</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>Test {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">static</span> <span class="keywordtype">bool</span> HasFatalFailure();</div>
<div class="line">};</div>
</div><!-- fragment --><p>The typical usage, which basically simulates the behavior of a thrown exception, is:</p>
<div class="fragment"><div class="line">TEST(FooTest, Bar) {</div>
<div class="line">  Subroutine();</div>
<div class="line">  <span class="comment">// Aborts if Subroutine() had a fatal failure.</span></div>
<div class="line">  <span class="keywordflow">if</span> (HasFatalFailure()) <span class="keywordflow">return</span>;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// The following won&#39;t be executed.</span></div>
<div class="line">  ...</div>
<div class="line">}</div>
</div><!-- fragment --><p>If <code>HasFatalFailure()</code> is used outside of <code>TEST()</code> , <code>TEST_F()</code> , or a test fixture, you must add the <code><a class="el" href="classtesting_1_1_test.html">testing::Test</a>::</code> prefix, as in:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (testing::Test::HasFatalFailure()) <span class="keywordflow">return</span>;</div>
</div><!-- fragment --><p>Similarly, <code>HasNonfatalFailure()</code> returns <code>true</code> if the current test has at least one non-fatal failure, and <code>HasFailure()</code> returns <code>true</code> if the current test has at least one failure of either kind.</p>
<h1><a class="anchor" id="autotoc_md42"></a>
Logging Additional Information</h1>
<p>In your test code, you can call <code>RecordProperty("key", value)</code> to log additional information, where <code>value</code> can be either a string or an <code>int</code>. The <em>last</em> value recorded for a key will be emitted to the XML output if you specify one. For example, the test</p>
<div class="fragment"><div class="line">TEST_F(WidgetUsageTest, MinAndMaxWidgets) {</div>
<div class="line">  RecordProperty(<span class="stringliteral">&quot;MaximumWidgets&quot;</span>, ComputeMaxUsage());</div>
<div class="line">  RecordProperty(<span class="stringliteral">&quot;MinimumWidgets&quot;</span>, ComputeMinUsage());</div>
<div class="line">}</div>
</div><!-- fragment --><p>will output XML like this:</p>
<div class="fragment"><div class="line">...</div>
<div class="line">  &lt;<span class="keywordtype">testcase</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;MinAndMaxWidgets&quot;</span> <span class="keyword">file</span>=<span class="stringliteral">&quot;test.cpp&quot;</span> <span class="keyword">line</span>=<span class="stringliteral">&quot;1&quot;</span> <span class="keyword">status</span>=<span class="stringliteral">&quot;run&quot;</span> <span class="keyword">time</span>=<span class="stringliteral">&quot;0.006&quot;</span> <span class="keyword">classname</span>=<span class="stringliteral">&quot;WidgetUsageTest&quot;</span> <span class="keyword">MaximumWidgets</span>=<span class="stringliteral">&quot;12&quot;</span> <span class="keyword">MinimumWidgets</span>=<span class="stringliteral">&quot;9&quot;</span> /&gt;</div>
<div class="line">...</div>
</div><!-- fragment --><p>{: .callout .note} </p><blockquote class="doxtable">
<p>NOTE:</p>
<ul>
<li><code>RecordProperty()</code> is a static member of the <code>Test</code> class. Therefore it needs to be prefixed with <code><a class="el" href="classtesting_1_1_test.html">testing::Test</a>::</code> if used outside of the <code>TEST</code> body and the test fixture class.</li>
<li><em><code>key</code></em> must be a valid XML attribute name, and cannot conflict with the ones already used by googletest (<code>name</code>, <code>status</code>, <code>time</code>, <code>classname</code>, <code>type_param</code>, and <code>value_param</code>).</li>
<li>Calling <code>RecordProperty()</code> outside of the lifespan of a test is allowed. If it's called outside of a test but between a test suite's <code>SetUpTestSuite()</code> and <code>TearDownTestSuite()</code> methods, it will be attributed to the XML element for the test suite. If it's called outside of all test suites (e.g. in a test environment), it will be attributed to the top-level XML element. </li>
</ul>
</blockquote>
<h1><a class="anchor" id="autotoc_md43"></a>
Sharing Resources Between Tests in the Same Test Suite</h1>
<p>googletest creates a new test fixture object for each test in order to make tests independent and easier to debug. However, sometimes tests use resources that are expensive to set up, making the one-copy-per-test model prohibitively expensive.</p>
<p>If the tests don't change the resource, there's no harm in their sharing a single resource copy. So, in addition to per-test set-up/tear-down, googletest also supports per-test-suite set-up/tear-down. To use it:</p>
<ol type="1">
<li>In your test fixture class (say <code><a class="el" href="class_foo_test.html">FooTest</a></code> ), declare as <code>static</code> some member variables to hold the shared resources.</li>
<li>Outside your test fixture class (typically just below it), define those member variables, optionally giving them initial values.</li>
<li>In the same test fixture class, define a <code>static void SetUpTestSuite()</code> function (remember not to spell it as <b><code>SetupTestSuite</code></b> with a small <code>u</code>!) to set up the shared resources and a <code>static void TearDownTestSuite()</code> function to tear them down.</li>
</ol>
<p>That's it! googletest automatically calls <code>SetUpTestSuite()</code> before running the <em>first test</em> in the <code><a class="el" href="class_foo_test.html">FooTest</a></code> test suite (i.e. before creating the first <code><a class="el" href="class_foo_test.html">FooTest</a></code> object), and calls <code>TearDownTestSuite()</code> after running the <em>last test</em> in it (i.e. after deleting the last <code><a class="el" href="class_foo_test.html">FooTest</a></code> object). In between, the tests can use the shared resources.</p>
<p>Remember that the test order is undefined, so your code can't depend on a test preceding or following another. Also, the tests must either not modify the state of any shared resource, or, if they do modify the state, they must restore the state to its original value before passing control to the next test.</p>
<p>Note that <code>SetUpTestSuite()</code> may be called multiple times for a test fixture class that has derived classes, so you should not expect code in the function body to be run only once. Also, derived classes still have access to shared resources defined as static members, so careful consideration is needed when managing shared resources to avoid memory leaks.</p>
<p>Here's an example of per-test-suite set-up and tear-down:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>FooTest : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test.html">testing::Test</a> {</div>
<div class="line"> <span class="keyword">protected</span>:</div>
<div class="line">  <span class="comment">// Per-test-suite set-up.</span></div>
<div class="line">  <span class="comment">// Called before the first test in this test suite.</span></div>
<div class="line">  <span class="comment">// Can be omitted if not needed.</span></div>
<div class="line">  <span class="keyword">static</span> <span class="keywordtype">void</span> SetUpTestSuite() {</div>
<div class="line">    <span class="comment">// Avoid reallocating static objects if called in subclasses of FooTest.</span></div>
<div class="line">    <span class="keywordflow">if</span> (shared_resource_ == <span class="keyword">nullptr</span>) {</div>
<div class="line">      shared_resource_ = <span class="keyword">new</span> ...;</div>
<div class="line">    }</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Per-test-suite tear-down.</span></div>
<div class="line">  <span class="comment">// Called after the last test in this test suite.</span></div>
<div class="line">  <span class="comment">// Can be omitted if not needed.</span></div>
<div class="line">  <span class="keyword">static</span> <span class="keywordtype">void</span> TearDownTestSuite() {</div>
<div class="line">    <span class="keyword">delete</span> shared_resource_;</div>
<div class="line">    shared_resource_ = <span class="keyword">nullptr</span>;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// You can define per-test set-up logic as usual.</span></div>
<div class="line">  <span class="keywordtype">void</span> SetUp()<span class="keyword"> override </span>{ ... }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// You can define per-test tear-down logic as usual.</span></div>
<div class="line">  <span class="keywordtype">void</span> TearDown()<span class="keyword"> override </span>{ ... }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Some expensive resource shared by all tests.</span></div>
<div class="line">  <span class="keyword">static</span> T* shared_resource_;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">T* FooTest::shared_resource_ = <span class="keyword">nullptr</span>;</div>
<div class="line"> </div>
<div class="line">TEST_F(FooTest, Test1) {</div>
<div class="line">  ... you can refer to shared_resource_ here ...</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TEST_F(FooTest, Test2) {</div>
<div class="line">  ... you can refer to shared_resource_ here ...</div>
<div class="line">}</div>
</div><!-- fragment --><p>{: .callout .note} NOTE: Though the above code declares <code>SetUpTestSuite()</code> protected, it may sometimes be necessary to declare it public, such as when using it with <code>TEST_P</code>.</p>
<h1><a class="anchor" id="autotoc_md44"></a>
Global Set-Up and Tear-Down</h1>
<p>Just as you can do set-up and tear-down at the test level and the test suite level, you can also do it at the test program level. Here's how.</p>
<p>First, you subclass the <code><a class="el" href="classtesting_1_1_environment.html">testing::Environment</a></code> class to define a test environment, which knows how to set-up and tear-down:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span><a class="code hl_class" href="class_environment.html">Environment</a> : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_environment.html">::testing::Environment</a> {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code hl_class" href="class_environment.html">~Environment</a>()<span class="keyword"> override </span>{}</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Override this to define how to set up the environment.</span></div>
<div class="line">  <span class="keywordtype">void</span> SetUp()<span class="keyword"> override </span>{}</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Override this to define how to tear down the environment.</span></div>
<div class="line">  <span class="keywordtype">void</span> TearDown()<span class="keyword"> override </span>{}</div>
<div class="line">};</div>
<div class="ttc" id="aclass_environment_html"><div class="ttname"><a href="class_environment.html">Environment</a></div><div class="ttdef"><b>Definition</b> gtest.h:887</div></div>
<div class="ttc" id="aclasstesting_1_1_environment_html"><div class="ttname"><a href="classtesting_1_1_environment.html">testing::Environment</a></div><div class="ttdef"><b>Definition</b> gtest.h:887</div></div>
</div><!-- fragment --><p>Then, you register an instance of your environment class with googletest by calling the <code>testing::AddGlobalTestEnvironment()</code> function:</p>
<div class="fragment"><div class="line"><a class="code hl_class" href="class_environment.html">Environment</a>* AddGlobalTestEnvironment(<a class="code hl_class" href="class_environment.html">Environment</a>* env);</div>
</div><!-- fragment --><p>Now, when <code>RUN_ALL_TESTS()</code> is called, it first calls the <code>SetUp()</code> method of each environment object, then runs the tests if none of the environments reported fatal failures and <code>GTEST_SKIP()</code> was not called. <code>RUN_ALL_TESTS()</code> always calls <code>TearDown()</code> with each environment object, regardless of whether or not the tests were run.</p>
<p>It's OK to register multiple environment objects. In this suite, their <code>SetUp()</code> will be called in the order they are registered, and their <code>TearDown()</code> will be called in the reverse order.</p>
<p>Note that googletest takes ownership of the registered environment objects. Therefore <b>do not delete them</b> by yourself.</p>
<p>You should call <code>AddGlobalTestEnvironment()</code> before <code>RUN_ALL_TESTS()</code> is called, probably in <code>main()</code>. If you use <code>gtest_main</code>, you need to call this before <code>main()</code> starts for it to take effect. One way to do this is to define a global variable like this:</p>
<div class="fragment"><div class="line"><a class="code hl_class" href="classtesting_1_1_environment.html">testing::Environment</a>* <span class="keyword">const</span> foo_env =</div>
<div class="line">    testing::AddGlobalTestEnvironment(<span class="keyword">new</span> <a class="code hl_class" href="class_foo_environment.html">FooEnvironment</a>);</div>
<div class="ttc" id="aclass_foo_environment_html"><div class="ttname"><a href="class_foo_environment.html">FooEnvironment</a></div><div class="ttdef"><b>Definition</b> googletest-output-test_.cc:983</div></div>
</div><!-- fragment --><p>However, we strongly recommend you to write your own <code>main()</code> and call <code>AddGlobalTestEnvironment()</code> there, as relying on initialization of global variables makes the code harder to read and may cause problems when you register multiple environments from different translation units and the environments have dependencies among them (remember that the compiler doesn't guarantee the order in which global variables from different translation units are initialized).</p>
<h1><a class="anchor" id="autotoc_md45"></a>
Value-Parameterized Tests</h1>
<p><em>Value-parameterized tests</em> allow you to test your code with different parameters without writing multiple copies of the same test. This is useful in a number of situations, for example:</p>
<ul>
<li>You have a piece of code whose behavior is affected by one or more command-line flags. You want to make sure your code performs correctly for various values of those flags.</li>
<li>You want to test different implementations of an OO interface.</li>
<li>You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it!</li>
</ul>
<h2><a class="anchor" id="autotoc_md46"></a>
How to Write Value-Parameterized Tests</h2>
<p>To write value-parameterized tests, first you should define a fixture class. It must be derived from both <code><a class="el" href="classtesting_1_1_test.html">testing::Test</a></code> and <code><a class="el" href="classtesting_1_1_with_param_interface.html">testing::WithParamInterface</a>&lt;T&gt;</code> (the latter is a pure interface), where <code>T</code> is the type of your parameter values. For convenience, you can just derive the fixture class from <code><a class="el" href="classtesting_1_1_test_with_param.html">testing::TestWithParam</a>&lt;T&gt;</code>, which itself is derived from both <code><a class="el" href="classtesting_1_1_test.html">testing::Test</a></code> and <code><a class="el" href="classtesting_1_1_with_param_interface.html">testing::WithParamInterface</a>&lt;T&gt;</code>. <code>T</code> can be any copyable type. If it's a raw pointer, you are responsible for managing the lifespan of the pointed values.</p>
<p>{: .callout .note} NOTE: If your test fixture defines <code>SetUpTestSuite()</code> or <code>TearDownTestSuite()</code> they must be declared <b>public</b> rather than <b>protected</b> in order to use <code>TEST_P</code>.</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>FooTest :</div>
<div class="line">    <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test_with_param.html">testing::TestWithParam</a>&lt;const char*&gt; {</div>
<div class="line">  <span class="comment">// You can implement all the usual fixture class members here.</span></div>
<div class="line">  <span class="comment">// To access the test parameter, call GetParam() from class</span></div>
<div class="line">  <span class="comment">// TestWithParam&lt;T&gt;.</span></div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="comment">// Or, when you want to add parameters to a pre-existing fixture class:</span></div>
<div class="line"><span class="keyword">class </span>BaseTest : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test.html">testing::Test</a> {</div>
<div class="line">  ...</div>
<div class="line">};</div>
<div class="line"><span class="keyword">class </span>BarTest : <span class="keyword">public</span> BaseTest,</div>
<div class="line">                <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_with_param_interface.html">testing::WithParamInterface</a>&lt;const char*&gt; {</div>
<div class="line">  ...</div>
<div class="line">};</div>
<div class="ttc" id="aclasstesting_1_1_test_with_param_html"><div class="ttname"><a href="classtesting_1_1_test_with_param.html">testing::TestWithParam</a></div><div class="ttdef"><b>Definition</b> gtest.h:1698</div></div>
<div class="ttc" id="aclasstesting_1_1_with_param_interface_html"><div class="ttname"><a href="classtesting_1_1_with_param_interface.html">testing::WithParamInterface</a></div><div class="ttdef"><b>Definition</b> gtest.h:1664</div></div>
</div><!-- fragment --><p>Then, use the <code>TEST_P</code> macro to define as many test patterns using this fixture as you want. The <code>_P</code> suffix is for "parameterized" or "pattern", whichever you prefer to think.</p>
<div class="fragment"><div class="line">TEST_P(FooTest, DoesBlah) {</div>
<div class="line">  <span class="comment">// Inside a test, access the test parameter with the GetParam() method</span></div>
<div class="line">  <span class="comment">// of the TestWithParam&lt;T&gt; class:</span></div>
<div class="line">  EXPECT_TRUE(foo.Blah(GetParam()));</div>
<div class="line">  ...</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TEST_P(FooTest, HasBlahBlah) {</div>
<div class="line">  ...</div>
<div class="line">}</div>
</div><!-- fragment --><p>Finally, you can use the <code>INSTANTIATE_TEST_SUITE_P</code> macro to instantiate the test suite with any set of parameters you want. GoogleTest defines a number of functions for generating test parameters—see details at <a href="reference/testing.md#INSTANTIATE_TEST_SUITE_P"><code>INSTANTIATE_TEST_SUITE_P</code></a> in the Testing Reference.</p>
<p>For example, the following statement will instantiate tests from the <code><a class="el" href="class_foo_test.html">FooTest</a></code> test suite each with parameter values <code>"meeny"</code>, <code>"miny"</code>, and <code>"moe"</code> using the <a href="reference/testing.md#param-generators"><code>Values</code></a> parameter generator:</p>
<div class="fragment"><div class="line">INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe,</div>
<div class="line">                         FooTest,</div>
<div class="line">                         testing::Values(<span class="stringliteral">&quot;meeny&quot;</span>, <span class="stringliteral">&quot;miny&quot;</span>, <span class="stringliteral">&quot;moe&quot;</span>));</div>
</div><!-- fragment --><p>{: .callout .note} NOTE: The code above must be placed at global or namespace scope, not at function scope.</p>
<p>The first argument to <code>INSTANTIATE_TEST_SUITE_P</code> is a unique name for the instantiation of the test suite. The next argument is the name of the test pattern, and the last is the <a href="reference/testing.md#param-generators">parameter generator</a>.</p>
<p>The parameter generator expression is not evaluated until GoogleTest is initialized (via <code>InitGoogleTest()</code>). Any prior initialization done in the <code>main</code> function will be accessible from the parameter generator, for example, the results of flag parsing.</p>
<p>You can instantiate a test pattern more than once, so to distinguish different instances of the pattern, the instantiation name is added as a prefix to the actual test suite name. Remember to pick unique prefixes for different instantiations. The tests from the instantiation above will have these names:</p>
<ul>
<li><code>MeenyMinyMoe/FooTest.DoesBlah/0</code> for <code>"meeny"</code></li>
<li><code>MeenyMinyMoe/FooTest.DoesBlah/1</code> for <code>"miny"</code></li>
<li><code>MeenyMinyMoe/FooTest.DoesBlah/2</code> for <code>"moe"</code></li>
<li><code>MeenyMinyMoe/FooTest.HasBlahBlah/0</code> for <code>"meeny"</code></li>
<li><code>MeenyMinyMoe/FooTest.HasBlahBlah/1</code> for <code>"miny"</code></li>
<li><code>MeenyMinyMoe/FooTest.HasBlahBlah/2</code> for <code>"moe"</code></li>
</ul>
<p>You can use these names in `--gtest_filter`.</p>
<p>The following statement will instantiate all tests from <code><a class="el" href="class_foo_test.html">FooTest</a></code> again, each with parameter values <code>"cat"</code> and <code>"dog"</code> using the <a href="reference/testing.md#param-generators"><code>ValuesIn</code></a> parameter generator:</p>
<div class="fragment"><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span>* pets[] = {<span class="stringliteral">&quot;cat&quot;</span>, <span class="stringliteral">&quot;dog&quot;</span>};</div>
<div class="line">INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets));</div>
</div><!-- fragment --><p>The tests from the instantiation above will have these names:</p>
<ul>
<li><code>Pets/FooTest.DoesBlah/0</code> for <code>"cat"</code></li>
<li><code>Pets/FooTest.DoesBlah/1</code> for <code>"dog"</code></li>
<li><code>Pets/FooTest.HasBlahBlah/0</code> for <code>"cat"</code></li>
<li><code>Pets/FooTest.HasBlahBlah/1</code> for <code>"dog"</code></li>
</ul>
<p>Please note that <code>INSTANTIATE_TEST_SUITE_P</code> will instantiate <em>all</em> tests in the given test suite, whether their definitions come before or <em>after</em> the <code>INSTANTIATE_TEST_SUITE_P</code> statement.</p>
<p>Additionally, by default, every <code>TEST_P</code> without a corresponding <code>INSTANTIATE_TEST_SUITE_P</code> causes a failing test in test suite <code>GoogleTestVerification</code>. If you have a test suite where that omission is not an error, for example it is in a library that may be linked in for other reasons or where the list of test cases is dynamic and may be empty, then this check can be suppressed by tagging the test suite:</p>
<div class="fragment"><div class="line">GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);</div>
</div><!-- fragment --><p>You can see <a href="https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc" title="Parameterized Test example">sample7_unittest.cc</a> and <a href="https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc" title="Parameterized Test example with multiple parameters">sample8_unittest.cc</a> for more examples.</p>
<h2><a class="anchor" id="autotoc_md47"></a>
Creating Value-Parameterized Abstract Tests</h2>
<p>In the above, we define and instantiate <code><a class="el" href="class_foo_test.html">FooTest</a></code> in the <em>same</em> source file. Sometimes you may want to define value-parameterized tests in a library and let other people instantiate them later. This pattern is known as <em>abstract tests</em>. As an example of its application, when you are designing an interface you can write a standard suite of abstract tests (perhaps using a factory function as the test parameter) that all implementations of the interface are expected to pass. When someone implements the interface, they can instantiate your suite to get all the interface-conformance tests for free.</p>
<p>To define abstract tests, you should organize your code like this:</p>
<ol type="1">
<li>Put the definition of the parameterized test fixture class (e.g. <code><a class="el" href="class_foo_test.html">FooTest</a></code>) in a header file, say <code>foo_param_test.h</code>. Think of this as <em>declaring</em> your abstract tests.</li>
<li>Put the <code>TEST_P</code> definitions in <code>foo_param_test.cc</code>, which includes <code>foo_param_test.h</code>. Think of this as <em>implementing</em> your abstract tests.</li>
</ol>
<p>Once they are defined, you can instantiate them by including <code>foo_param_test.h</code>, invoking <code>INSTANTIATE_TEST_SUITE_P()</code>, and depending on the library target that contains <code>foo_param_test.cc</code>. You can instantiate the same abstract test suite multiple times, possibly in different source files.</p>
<h2><a class="anchor" id="autotoc_md48"></a>
Specifying Names for Value-Parameterized Test Parameters</h2>
<p>The optional last argument to <code>INSTANTIATE_TEST_SUITE_P()</code> allows the user to specify a function or functor that generates custom test name suffixes based on the test parameters. The function should accept one argument of type <code><a class="el" href="structtesting_1_1_test_param_info.html">testing::TestParamInfo</a>&lt;class ParamType&gt;</code>, and return <code>std::string</code>.</p>
<p><code><a class="el" href="structtesting_1_1_print_to_string_param_name.html">testing::PrintToStringParamName</a></code> is a builtin test suffix generator that returns the value of <code>testing::PrintToString(GetParam())</code>. It does not work for <code>std::string</code> or C strings.</p>
<p>{: .callout .note} NOTE: test names must be non-empty, unique, and may only contain ASCII alphanumeric characters. In particular, they <a href="faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore">should not contain underscores</a></p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MyTestSuite : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test_with_param.html">testing::TestWithParam</a>&lt;int&gt; {};</div>
<div class="line"> </div>
<div class="line">TEST_P(MyTestSuite, MyTest)</div>
<div class="line">{</div>
<div class="line">  std::cout &lt;&lt; <span class="stringliteral">&quot;Example Test Param: &quot;</span> &lt;&lt; GetParam() &lt;&lt; std::endl;</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">INSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10),</div>
<div class="line">                         <a class="code hl_struct" href="structtesting_1_1_print_to_string_param_name.html">testing::PrintToStringParamName</a>());</div>
<div class="ttc" id="astructtesting_1_1_print_to_string_param_name_html"><div class="ttname"><a href="structtesting_1_1_print_to_string_param_name.html">testing::PrintToStringParamName</a></div><div class="ttdef"><b>Definition</b> gtest-param-util.h:68</div></div>
</div><!-- fragment --><p>Providing a custom functor allows for more control over test parameter name generation, especially for types where the automatic conversion does not generate helpful parameter names (e.g. strings as demonstrated above). The following example illustrates this for multiple parameters, an enumeration type and a string, and also demonstrates how to combine generators. It uses a lambda for conciseness:</p>
<div class="fragment"><div class="line"><span class="keyword">enum class</span> <a class="code hl_class" href="class_my_type.html">MyType</a> { MY_FOO = 0, MY_BAR = 1 };</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MyTestSuite : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test_with_param.html">testing::TestWithParam</a>&lt;std::tuple&lt;MyType, std::string&gt;&gt; {</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">INSTANTIATE_TEST_SUITE_P(</div>
<div class="line">    MyGroup, MyTestSuite,</div>
<div class="line">    testing::Combine(</div>
<div class="line">        testing::Values(MyType::MY_FOO, MyType::MY_BAR),</div>
<div class="line">        testing::Values(<span class="stringliteral">&quot;A&quot;</span>, <span class="stringliteral">&quot;B&quot;</span>)),</div>
<div class="line">    [](<span class="keyword">const</span> <a class="code hl_struct" href="structtesting_1_1_test_param_info.html">testing::TestParamInfo&lt;MyTestSuite::ParamType&gt;</a>&amp; info) {</div>
<div class="line">      std::string name = absl::StrCat(</div>
<div class="line">          std::get&lt;0&gt;(info.param) == MyType::MY_FOO ? <span class="stringliteral">&quot;Foo&quot;</span> : <span class="stringliteral">&quot;Bar&quot;</span>,</div>
<div class="line">          std::get&lt;1&gt;(info.param));</div>
<div class="line">      absl::c_replace_if(name, [](<span class="keywordtype">char</span> c) { <span class="keywordflow">return</span> !std::isalnum(c); }, <span class="charliteral">&#39;_&#39;</span>);</div>
<div class="line">      <span class="keywordflow">return</span> name;</div>
<div class="line">    });</div>
<div class="ttc" id="aclass_my_type_html"><div class="ttname"><a href="class_my_type.html">MyType</a></div><div class="ttdef"><b>Definition</b> googletest-list-tests-unittest_.cc:66</div></div>
<div class="ttc" id="astructtesting_1_1_test_param_info_html"><div class="ttname"><a href="structtesting_1_1_test_param_info.html">testing::TestParamInfo</a></div><div class="ttdef"><b>Definition</b> gtest-param-util.h:59</div></div>
</div><!-- fragment --><h1><a class="anchor" id="autotoc_md49"></a>
Typed Tests</h1>
<p>Suppose you have multiple implementations of the same interface and want to make sure that all of them satisfy some common requirements. Or, you may have defined several types that are supposed to conform to the same "concept" and you want to verify it. In both cases, you want the same test logic repeated for different types.</p>
<p>While you can write one <code>TEST</code> or <code>TEST_F</code> for each type you want to test (and you may even factor the test logic into a function template that you invoke from the <code>TEST</code>), it's tedious and doesn't scale: if you want <code>m</code> tests over <code>n</code> types, you'll end up writing <code>m*n</code> <code>TEST</code>s.</p>
<p><em>Typed tests</em> allow you to repeat the same test logic over a list of types. You only need to write the test logic once, although you must know the type list when writing typed tests. Here's how you do it:</p>
<p>First, define a fixture class template. It should be parameterized by a type. Remember to derive it from <code><a class="el" href="classtesting_1_1_test.html">testing::Test</a></code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line"><span class="keyword">class </span>FooTest : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test.html">testing::Test</a> {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">using </span>List = std::list&lt;T&gt;;</div>
<div class="line">  <span class="keyword">static</span> T shared_;</div>
<div class="line">  T value_;</div>
<div class="line">};</div>
</div><!-- fragment --><p>Next, associate a list of types with the test suite, which will be repeated for each type in the list:</p>
<div class="fragment"><div class="line"><span class="keyword">using </span>MyTypes = ::testing::Types&lt;char, int, unsigned int&gt;;</div>
<div class="line">TYPED_TEST_SUITE(FooTest, MyTypes);</div>
</div><!-- fragment --><p>The type alias (<code>using</code> or <code>typedef</code>) is necessary for the <code>TYPED_TEST_SUITE</code> macro to parse correctly. Otherwise the compiler will think that each comma in the type list introduces a new macro argument.</p>
<p>Then, use <code>TYPED_TEST()</code> instead of <code>TEST_F()</code> to define a typed test for this test suite. You can repeat this as many times as you want:</p>
<div class="fragment"><div class="line">TYPED_TEST(FooTest, DoesBlah) {</div>
<div class="line">  <span class="comment">// Inside a test, refer to the special name TypeParam to get the type</span></div>
<div class="line">  <span class="comment">// parameter.  Since we are inside a derived class template, C++ requires</span></div>
<div class="line">  <span class="comment">// us to visit the members of FooTest via &#39;this&#39;.</span></div>
<div class="line">  TypeParam n = this-&gt;value_;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// To visit static members of the fixture, add the &#39;TestFixture::&#39;</span></div>
<div class="line">  <span class="comment">// prefix.</span></div>
<div class="line">  n += TestFixture::shared_;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// To refer to typedefs in the fixture, add the &#39;typename TestFixture::&#39;</span></div>
<div class="line">  <span class="comment">// prefix.  The &#39;typename&#39; is required to satisfy the compiler.</span></div>
<div class="line">  <span class="keyword">typename</span> TestFixture::List values;</div>
<div class="line"> </div>
<div class="line">  values.push_back(n);</div>
<div class="line">  ...</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TYPED_TEST(FooTest, HasPropertyA) { ... }</div>
</div><!-- fragment --><p>You can see <a href="https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc" title="Typed Test example">sample6_unittest.cc</a> for a complete example.</p>
<h1><a class="anchor" id="autotoc_md50"></a>
Type-Parameterized Tests</h1>
<p><em>Type-parameterized tests</em> are like typed tests, except that they don't require you to know the list of types ahead of time. Instead, you can define the test logic first and instantiate it with different type lists later. You can even instantiate it more than once in the same program.</p>
<p>If you are designing an interface or concept, you can define a suite of type-parameterized tests to verify properties that any valid implementation of the interface/concept should have. Then, the author of each implementation can just instantiate the test suite with their type to verify that it conforms to the requirements, without having to write similar tests repeatedly. Here's an example:</p>
<p>First, define a fixture class template, as we did with typed tests:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line"><span class="keyword">class </span>FooTest : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test.html">testing::Test</a> {</div>
<div class="line">  <span class="keywordtype">void</span> DoSomethingInteresting();</div>
<div class="line">  ...</div>
<div class="line">};</div>
</div><!-- fragment --><p>Next, declare that you will define a type-parameterized test suite:</p>
<div class="fragment"><div class="line">TYPED_TEST_SUITE_P(FooTest);</div>
</div><!-- fragment --><p>Then, use <code>TYPED_TEST_P()</code> to define a type-parameterized test. You can repeat this as many times as you want:</p>
<div class="fragment"><div class="line">TYPED_TEST_P(FooTest, DoesBlah) {</div>
<div class="line">  <span class="comment">// Inside a test, refer to TypeParam to get the type parameter.</span></div>
<div class="line">  TypeParam n = 0;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// You will need to use `this` explicitly to refer to fixture members.</span></div>
<div class="line">  this-&gt;DoSomethingInteresting()</div>
<div class="line">  ...</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">TYPED_TEST_P(FooTest, HasPropertyA) { ... }</div>
</div><!-- fragment --><p>Now the tricky part: you need to register all test patterns using the <code>REGISTER_TYPED_TEST_SUITE_P</code> macro before you can instantiate them. The first argument of the macro is the test suite name; the rest are the names of the tests in this test suite:</p>
<div class="fragment"><div class="line">REGISTER_TYPED_TEST_SUITE_P(FooTest,</div>
<div class="line">                            DoesBlah, HasPropertyA);</div>
</div><!-- fragment --><p>Finally, you are free to instantiate the pattern with the types you want. If you put the above code in a header file, you can <code>#include</code> it in multiple C++ source files and instantiate it multiple times.</p>
<div class="fragment"><div class="line"><span class="keyword">using </span>MyTypes = ::testing::Types&lt;char, int, unsigned int&gt;;</div>
<div class="line">INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);</div>
</div><!-- fragment --><p>To distinguish different instances of the pattern, the first argument to the <code>INSTANTIATE_TYPED_TEST_SUITE_P</code> macro is a prefix that will be added to the actual test suite name. Remember to pick unique prefixes for different instances.</p>
<p>In the special case where the type list contains only one type, you can write that type directly without <code>testing::Types&lt;...&gt;</code>, like this:</p>
<div class="fragment"><div class="line">INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, <span class="keywordtype">int</span>);</div>
</div><!-- fragment --><p>You can see <a href="https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc" title="Typed Test example">sample6_unittest.cc</a> for a complete example.</p>
<h1><a class="anchor" id="autotoc_md51"></a>
Testing Private Code</h1>
<p>If you change your software's internal implementation, your tests should not break as long as the change is not observable by users. Therefore, <b>per the black-box testing principle, most of the time you should test your code through its public interfaces.</b></p>
<p><b>If you still find yourself needing to test internal implementation code, consider if there's a better design.</b> The desire to test internal implementation is often a sign that the class is doing too much. Consider extracting an implementation class, and testing it. Then use that implementation class in the original class.</p>
<p>If you absolutely have to test non-public interface code though, you can. There are two cases to consider:</p>
<ul>
<li>Static functions ( <em>not</em> the same as static member functions!) or unnamed namespaces, and</li>
<li>Private or protected class members</li>
</ul>
<p>To test them, we use the following special techniques:</p>
<ul>
<li><p class="startli">Both static functions and definitions/declarations in an unnamed namespace are only visible within the same translation unit. To test them, you can <code>#include</code> the entire <code>.cc</code> file being tested in your <code>*_test.cc</code> file. (#including <code>.cc</code> files is not a good way to reuse code - you should not do this in production code!)</p>
<p class="startli">However, a better approach is to move the private code into the <code>foo::internal</code> namespace, where <code>foo</code> is the namespace your project normally uses, and put the private declarations in a <code>*-internal.h</code> file. Your production <code>.cc</code> files and your tests are allowed to include this internal header, but your clients are not. This way, you can fully test your internal implementation without leaking it to your clients.</p>
</li>
<li><p class="startli">Private class members are only accessible from within the class or by friends. To access a class' private members, you can declare your test fixture as a friend to the class and define accessors in your fixture. Tests using the fixture can then access the private members of your production class via the accessors in the fixture. Note that even though your fixture is a friend to your production class, your tests are not automatically friends to it, as they are technically defined in sub-classes of the fixture.</p>
<p class="startli">Another way to test private members is to refactor them into an implementation class, which is then declared in a <code>*-internal.h</code> file. Your clients aren't allowed to include this header but your tests can. Such is called the <a href="https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/">Pimpl</a> (Private Implementation) idiom.</p>
<p class="startli">Or, you can declare an individual test as a friend of your class by adding this line in the class body:</p>
<p class="startli"><code>c++ FRIEND_TEST(TestSuiteName, TestName); </code></p>
<p class="startli">For example,</p>
<p class="startli">```c++ // foo.h class Foo { ... private: FRIEND_TEST(FooTest, BarReturnsZeroOnNull);</p>
<p class="startli">int Bar(void* x); };</p>
<p class="startli">// foo_test.cc ... TEST(FooTest, BarReturnsZeroOnNull) { Foo foo; EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). } ```</p>
<p class="startli">Pay special attention when your class is defined in a namespace. If you want your test fixtures and tests to be friends of your class, then they must be defined in the exact same namespace (no anonymous or inline namespaces).</p>
<p class="startli">For example, if the code to be tested looks like:</p>
<p class="startli">```c++ namespace my_namespace {</p>
<p class="startli">class Foo { friend class <a class="el" href="class_foo_test.html">FooTest</a>; FRIEND_TEST(FooTest, Bar); FRIEND_TEST(FooTest, Baz); ... definition of the class Foo ... };</p>
<p class="startli">} // namespace my_namespace ```</p>
<p class="startli">Your test code should be something like:</p>
<p class="startli">```c++ namespace my_namespace {</p>
<p class="startli">class <a class="el" href="class_foo_test.html">FooTest</a> : public <a class="el" href="classtesting_1_1_test.html">testing::Test</a> { protected: ... };</p>
<p class="startli">TEST_F(FooTest, Bar) { ... } TEST_F(FooTest, Baz) { ... }</p>
<p class="startli">} // namespace my_namespace ```</p>
</li>
</ul>
<h1><a class="anchor" id="autotoc_md52"></a>
"Catching" Failures</h1>
<p>If you are building a testing utility on top of googletest, you'll want to test your utility. What framework would you use to test it? googletest, of course.</p>
<p>The challenge is to verify that your testing utility reports failures correctly. In frameworks that report a failure by throwing an exception, you could catch the exception and assert on it. But googletest doesn't use exceptions, so how do we test that a piece of code generates an expected failure?</p>
<p><code>"gtest/gtest-spi.h"</code> contains some constructs to do this. After #including this header, you can use</p>
<div class="fragment"><div class="line">EXPECT_FATAL_FAILURE(statement, substring);</div>
</div><!-- fragment --><p>to assert that <code>statement</code> generates a fatal (e.g. <code>ASSERT_*</code>) failure in the current thread whose message contains the given <code>substring</code>, or use</p>
<div class="fragment"><div class="line">EXPECT_NONFATAL_FAILURE(statement, substring);</div>
</div><!-- fragment --><p>if you are expecting a non-fatal (e.g. <code>EXPECT_*</code>) failure.</p>
<p>Only failures in the current thread are checked to determine the result of this type of expectations. If <code>statement</code> creates new threads, failures in these threads are also ignored. If you want to catch failures in other threads as well, use one of the following macros instead:</p>
<div class="fragment"><div class="line">EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring);</div>
<div class="line">EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring);</div>
</div><!-- fragment --><p>{: .callout .note} NOTE: Assertions from multiple threads are currently not supported on Windows.</p>
<p>For technical reasons, there are some caveats:</p>
<ol type="1">
<li>You cannot stream a failure message to either macro.</li>
<li><code>statement</code> in <code>EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()</code> cannot reference local non-static variables or non-static members of <code>this</code> object.</li>
<li><code>statement</code> in <code>EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()</code> cannot return a value.</li>
</ol>
<h1><a class="anchor" id="autotoc_md53"></a>
Registering tests programmatically</h1>
<p>The <code>TEST</code> macros handle the vast majority of all use cases, but there are few where runtime registration logic is required. For those cases, the framework provides the <code>testing::RegisterTest</code> that allows callers to register arbitrary tests dynamically.</p>
<p>This is an advanced API only to be used when the <code>TEST</code> macros are insufficient. The macros should be preferred when possible, as they avoid most of the complexity of calling this function.</p>
<p>It provides the following signature:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> Factory&gt;</div>
<div class="line"><a class="code hl_class" href="class_test_info.html">TestInfo</a>* RegisterTest(<span class="keyword">const</span> <span class="keywordtype">char</span>* test_suite_name, <span class="keyword">const</span> <span class="keywordtype">char</span>* test_name,</div>
<div class="line">                       <span class="keyword">const</span> <span class="keywordtype">char</span>* type_param, <span class="keyword">const</span> <span class="keywordtype">char</span>* value_param,</div>
<div class="line">                       <span class="keyword">const</span> <span class="keywordtype">char</span>* file, <span class="keywordtype">int</span> line, Factory factory);</div>
<div class="ttc" id="aclass_test_info_html"><div class="ttname"><a href="class_test_info.html">TestInfo</a></div><div class="ttdef"><b>Definition</b> gtest.h:527</div></div>
</div><!-- fragment --><p>The <code>factory</code> argument is a factory callable (move-constructible) object or function pointer that creates a new instance of the Test object. It handles ownership to the caller. The signature of the callable is <code>Fixture*()</code>, where <code><a class="el" href="class_fixture.html">Fixture</a></code> is the test fixture class for the test. All tests registered with the same <code>test_suite_name</code> must return the same fixture type. This is checked at runtime.</p>
<p>The framework will infer the fixture class from the factory and will call the <code>SetUpTestSuite</code> and <code>TearDownTestSuite</code> for it.</p>
<p>Must be called before <code>RUN_ALL_TESTS()</code> is invoked, otherwise behavior is undefined.</p>
<p>Use case example:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MyFixture : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test.html">testing::Test</a> {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="comment">// All of these optional, just like in regular macro usage.</span></div>
<div class="line">  <span class="keyword">static</span> <span class="keywordtype">void</span> SetUpTestSuite() { ... }</div>
<div class="line">  <span class="keyword">static</span> <span class="keywordtype">void</span> TearDownTestSuite() { ... }</div>
<div class="line">  <span class="keywordtype">void</span> SetUp()<span class="keyword"> override </span>{ ... }</div>
<div class="line">  <span class="keywordtype">void</span> TearDown()<span class="keyword"> override </span>{ ... }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MyTest : <span class="keyword">public</span> MyFixture {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">explicit</span> MyTest(<span class="keywordtype">int</span> data) : data_(data) {}</div>
<div class="line">  <span class="keywordtype">void</span> TestBody()<span class="keyword"> override </span>{ ... }</div>
<div class="line"> </div>
<div class="line"> <span class="keyword">private</span>:</div>
<div class="line">  <span class="keywordtype">int</span> data_;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">void</span> RegisterMyTests(<span class="keyword">const</span> std::vector&lt;int&gt;&amp; values) {</div>
<div class="line">  <span class="keywordflow">for</span> (<span class="keywordtype">int</span> v : values) {</div>
<div class="line">    testing::RegisterTest(</div>
<div class="line">        <span class="stringliteral">&quot;MyFixture&quot;</span>, (<span class="stringliteral">&quot;Test&quot;</span> + std::to_string(v)).c_str(), <span class="keyword">nullptr</span>,</div>
<div class="line">        std::to_string(v).c_str(),</div>
<div class="line">        __FILE__, __LINE__,</div>
<div class="line">        <span class="comment">// Important to use the fixture type as the return type here.</span></div>
<div class="line">        [=]() -&gt; MyFixture* { <span class="keywordflow">return</span> <span class="keyword">new</span> MyTest(v); });</div>
<div class="line">  }</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">int main(<span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv) {</div>
<div class="line">  testing::InitGoogleTest(&amp;argc, argv);</div>
<div class="line">  std::vector&lt;int&gt; values_to_test = LoadValuesFromConfig();</div>
<div class="line">  RegisterMyTests(values_to_test);</div>
<div class="line">  ...</div>
<div class="line">  <span class="keywordflow">return</span> RUN_ALL_TESTS();</div>
<div class="line">}</div>
</div><!-- fragment --><h1><a class="anchor" id="autotoc_md54"></a>
Getting the Current Test's Name</h1>
<p>Sometimes a function may need to know the name of the currently running test. For example, you may be using the <code>SetUp()</code> method of your test fixture to set the golden file name based on which test is running. The <a href="reference/testing.md#TestInfo"><code>TestInfo</code></a> class has this information.</p>
<p>To obtain a <code><a class="el" href="class_test_info.html">TestInfo</a></code> object for the currently running test, call <code>current_test_info()</code> on the <a href="reference/testing.md#UnitTest"><code>UnitTest</code></a> singleton object:</p>
<div class="fragment"><div class="line"><span class="comment">// Gets information about the currently running test.</span></div>
<div class="line"><span class="comment">// Do NOT delete the returned object - it&#39;s managed by the UnitTest class.</span></div>
<div class="line"><span class="keyword">const</span> <a class="code hl_class" href="classtesting_1_1_test_info.html">testing::TestInfo</a>* <span class="keyword">const</span> test_info =</div>
<div class="line">    testing::UnitTest::GetInstance()-&gt;current_test_info();</div>
<div class="line"> </div>
<div class="line">printf(<span class="stringliteral">&quot;We are in test %s of test suite %s.\n&quot;</span>,</div>
<div class="line">       test_info-&gt;name(),</div>
<div class="line">       test_info-&gt;test_suite_name());</div>
<div class="ttc" id="aclasstesting_1_1_test_info_html"><div class="ttname"><a href="classtesting_1_1_test_info.html">testing::TestInfo</a></div><div class="ttdef"><b>Definition</b> gtest.h:527</div></div>
</div><!-- fragment --><p><code>current_test_info()</code> returns a null pointer if no test is running. In particular, you cannot find the test suite name in <code>SetUpTestSuite()</code>, <code>TearDownTestSuite()</code> (where you know the test suite name implicitly), or functions called from them.</p>
<h1><a class="anchor" id="autotoc_md55"></a>
Extending googletest by Handling Test Events</h1>
<p>googletest provides an <b>event listener API</b> to let you receive notifications about the progress of a test program and test failures. The events you can listen to include the start and end of the test program, a test suite, or a test method, among others. You may use this API to augment or replace the standard console output, replace the XML output, or provide a completely different form of output, such as a GUI or a database. You can also use test events as checkpoints to implement a resource leak checker, for example.</p>
<h2><a class="anchor" id="autotoc_md56"></a>
Defining Event Listeners</h2>
<p>To define a event listener, you subclass either <a href="reference/testing.md#TestEventListener"><code>testing::TestEventListener</code></a> or <a href="reference/testing.md#EmptyTestEventListener"><code>testing::EmptyTestEventListener</code></a> The former is an (abstract) interface, where <em>each pure virtual method can be overridden to handle a test event</em> (For example, when a test starts, the <code>OnTestStart()</code> method will be called.). The latter provides an empty implementation of all methods in the interface, such that a subclass only needs to override the methods it cares about.</p>
<p>When an event is fired, its context is passed to the handler function as an argument. The following argument types are used:</p>
<ul>
<li><a class="el" href="class_unit_test.html">UnitTest</a> reflects the state of the entire test program,</li>
<li><a class="el" href="class_test_suite.html">TestSuite</a> has information about a test suite, which can contain one or more tests,</li>
<li><a class="el" href="class_test_info.html">TestInfo</a> contains the state of a test, and</li>
<li>TestPartResult represents the result of a test assertion.</li>
</ul>
<p>An event handler function can examine the argument it receives to find out interesting information about the event and the test program's state.</p>
<p>Here's an example:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MinimalistPrinter : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_empty_test_event_listener.html">testing::EmptyTestEventListener</a> {</div>
<div class="line">  <span class="comment">// Called before a test starts.</span></div>
<div class="line">  <span class="keywordtype">void</span> OnTestStart(<span class="keyword">const</span> <a class="code hl_class" href="classtesting_1_1_test_info.html">testing::TestInfo</a>&amp; test_info)<span class="keyword"> override </span>{</div>
<div class="line">    printf(<span class="stringliteral">&quot;*** Test %s.%s starting.\n&quot;</span>,</div>
<div class="line">           test_info.test_suite_name(), test_info.name());</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Called after a failed assertion or a SUCCESS().</span></div>
<div class="line">  <span class="keywordtype">void</span> OnTestPartResult(<span class="keyword">const</span> testing::TestPartResult&amp; test_part_result)<span class="keyword"> override </span>{</div>
<div class="line">    printf(<span class="stringliteral">&quot;%s in %s:%d\n%s\n&quot;</span>,</div>
<div class="line">           test_part_result.failed() ? <span class="stringliteral">&quot;*** Failure&quot;</span> : <span class="stringliteral">&quot;Success&quot;</span>,</div>
<div class="line">           test_part_result.file_name(),</div>
<div class="line">           test_part_result.line_number(),</div>
<div class="line">           test_part_result.summary());</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Called after a test ends.</span></div>
<div class="line">  <span class="keywordtype">void</span> OnTestEnd(<span class="keyword">const</span> testing::TestInfo&amp; test_info)<span class="keyword"> override </span>{</div>
<div class="line">    printf(<span class="stringliteral">&quot;*** Test %s.%s ending.\n&quot;</span>,</div>
<div class="line">           test_info.test_suite_name(), test_info.name());</div>
<div class="line">  }</div>
<div class="line">};</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md57"></a>
Using Event Listeners</h2>
<p>To use the event listener you have defined, add an instance of it to the googletest event listener list (represented by class <a href="reference/testing.md#TestEventListeners"><code>TestEventListeners</code></a> - note the "s" at the end of the name) in your <code>main()</code> function, before calling <code>RUN_ALL_TESTS()</code>:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv) {</div>
<div class="line">  testing::InitGoogleTest(&amp;argc, argv);</div>
<div class="line">  <span class="comment">// Gets hold of the event listener list.</span></div>
<div class="line">  <a class="code hl_class" href="classtesting_1_1_test_event_listeners.html">testing::TestEventListeners</a>&amp; listeners =</div>
<div class="line">      testing::UnitTest::GetInstance()-&gt;listeners();</div>
<div class="line">  <span class="comment">// Adds a listener to the end.  googletest takes the ownership.</span></div>
<div class="line">  listeners.Append(<span class="keyword">new</span> MinimalistPrinter);</div>
<div class="line">  <span class="keywordflow">return</span> RUN_ALL_TESTS();</div>
<div class="line">}</div>
<div class="ttc" id="aclasstesting_1_1_test_event_listeners_html"><div class="ttname"><a href="classtesting_1_1_test_event_listeners.html">testing::TestEventListeners</a></div><div class="ttdef"><b>Definition</b> gtest.h:1016</div></div>
</div><!-- fragment --><p>There's only one problem: the default test result printer is still in effect, so its output will mingle with the output from your minimalist printer. To suppress the default printer, just release it from the event listener list and delete it. You can do so by adding one line:</p>
<div class="fragment"><div class="line">...</div>
<div class="line">delete listeners.Release(listeners.default_result_printer());</div>
<div class="line">listeners.Append(<span class="keyword">new</span> MinimalistPrinter);</div>
<div class="line"><span class="keywordflow">return</span> RUN_ALL_TESTS();</div>
</div><!-- fragment --><p>Now, sit back and enjoy a completely different output from your tests. For more details, see <a href="https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc" title="Event listener example">sample9_unittest.cc</a>.</p>
<p>You may append more than one listener to the list. When an <code>On*Start()</code> or <code>OnTestPartResult()</code> event is fired, the listeners will receive it in the order they appear in the list (since new listeners are added to the end of the list, the default text printer and the default XML generator will receive the event first). An <code>On*End()</code> event will be received by the listeners in the <em>reverse</em> order. This allows output by listeners added later to be framed by output from listeners added earlier.</p>
<h2><a class="anchor" id="autotoc_md58"></a>
Generating Failures in Listeners</h2>
<p>You may use failure-raising macros (<code>EXPECT_*()</code>, <code>ASSERT_*()</code>, <code>FAIL()</code>, etc) when processing an event. There are some restrictions:</p>
<ol type="1">
<li>You cannot generate any failure in <code>OnTestPartResult()</code> (otherwise it will cause <code>OnTestPartResult()</code> to be called recursively).</li>
<li>A listener that handles <code>OnTestPartResult()</code> is not allowed to generate any failure.</li>
</ol>
<p>When you add listeners to the listener list, you should put listeners that handle <code>OnTestPartResult()</code> <em>before</em> listeners that can generate failures. This ensures that failures generated by the latter are attributed to the right test by the former.</p>
<p>See <a href="https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc" title="Failure-raising listener example">sample10_unittest.cc</a> for an example of a failure-raising listener.</p>
<h1><a class="anchor" id="autotoc_md59"></a>
Running Test Programs: Advanced Options</h1>
<p>googletest test programs are ordinary executables. Once built, you can run them directly and affect their behavior via the following environment variables and/or command line flags. For the flags to work, your programs must call <code>testing::InitGoogleTest()</code> before calling <code>RUN_ALL_TESTS()</code>.</p>
<p>To see a list of supported flags and their usage, please run your test program with the <code>--help</code> flag. You can also use <code>-h</code>, <code>-?</code>, or <code>/?</code> for short.</p>
<p>If an option is specified both by an environment variable and by a flag, the latter takes precedence.</p>
<h2><a class="anchor" id="autotoc_md60"></a>
Selecting Tests</h2>
<h3><a class="anchor" id="autotoc_md61"></a>
Listing Test Names</h3>
<p>Sometimes it is necessary to list the available tests in a program before running them so that a filter may be applied if needed. Including the flag <code>--gtest_list_tests</code> overrides all other flags and lists tests in the following format:</p>
<div class="fragment"><div class="line">TestSuite1.</div>
<div class="line">  TestName1</div>
<div class="line">  TestName2</div>
<div class="line">TestSuite2.</div>
<div class="line">  TestName</div>
</div><!-- fragment --><p>None of the tests listed are actually run if the flag is provided. There is no corresponding environment variable for this flag.</p>
<h3><a class="anchor" id="autotoc_md62"></a>
Running a Subset of the Tests</h3>
<p>By default, a googletest program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the <code>GTEST_FILTER</code> environment variable or the <code>--gtest_filter</code> flag to a filter string, googletest will only run the tests whose full names (in the form of <code>TestSuiteName.TestName</code>) match the filter.</p>
<p>The format of a filter is a '<code>:</code>'-separated list of wildcard patterns (called the <em>positive patterns</em>) optionally followed by a '<code>-</code>' and another '<code>:</code>'-separated pattern list (called the <em>negative patterns</em>). A test matches the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns.</p>
<p>A pattern may contain &lsquo;&rsquo;<em>'<code>(matches any string) or</code>'?'<code>(matches any single character). For convenience, the filter</code>'</em>-NegativePatterns'<code>can be also written as</code>'-NegativePatterns'`.</p>
<p>For example:</p>
<ul>
<li><code>./foo_test</code> Has no flag, and thus runs all its tests.</li>
<li><code>./foo_test --gtest_filter=*</code> Also runs everything, due to the single match-everything <code>*</code> value.</li>
<li><code>./foo_test --gtest_filter=<a class="el" href="class_foo_test.html">FooTest</a>.*</code> Runs everything in test suite <code><a class="el" href="class_foo_test.html">FooTest</a></code> .</li>
<li><code>./foo_test --gtest_filter=*Null*:*Constructor*</code> Runs any test whose full name contains either <code>"Null"</code> or <code>"Constructor"</code> .</li>
<li><code>./foo_test --gtest_filter=-*DeathTest.*</code> Runs all non-death tests.</li>
<li><code>./foo_test --gtest_filter=<a class="el" href="class_foo_test.html">FooTest</a>.*-FooTest.Bar</code> Runs everything in test suite <code><a class="el" href="class_foo_test.html">FooTest</a></code> except <code>FooTest.Bar</code>.</li>
<li><code>./foo_test --gtest_filter=<a class="el" href="class_foo_test.html">FooTest</a>.*:BarTest.*-FooTest.Bar:BarTest.Foo</code> Runs everything in test suite <code><a class="el" href="class_foo_test.html">FooTest</a></code> except <code>FooTest.Bar</code> and everything in test suite <code>BarTest</code> except <code>BarTest.Foo</code>.</li>
</ul>
<h3><a class="anchor" id="autotoc_md63"></a>
Stop test execution upon first failure</h3>
<p>By default, a googletest program runs all tests the user has defined. In some cases (e.g. iterative test development &amp; execution) it may be desirable stop test execution upon first failure (trading improved latency for completeness). If <code>GTEST_FAIL_FAST</code> environment variable or <code>--gtest_fail_fast</code> flag is set, the test runner will stop execution as soon as the first test failure is found.</p>
<h3><a class="anchor" id="autotoc_md64"></a>
Temporarily Disabling Tests</h3>
<p>If you have a broken test that you cannot fix right away, you can add the <code>DISABLED_</code> prefix to its name. This will exclude it from execution. This is better than commenting out the code or using <code>#if 0</code>, as disabled tests are still compiled (and thus won't rot).</p>
<p>If you need to disable all tests in a test suite, you can either add <code>DISABLED_</code> to the front of the name of each test, or alternatively add it to the front of the test suite name.</p>
<p>For example, the following tests won't be run by googletest, even though they will still be compiled:</p>
<div class="fragment"><div class="line"><span class="comment">// Tests that Foo does Abc.</span></div>
<div class="line">TEST(FooTest, DISABLED_DoesAbc) { ... }</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>DISABLED_BarTest : <span class="keyword">public</span> <a class="code hl_class" href="classtesting_1_1_test.html">testing::Test</a> { ... };</div>
<div class="line"> </div>
<div class="line"><span class="comment">// Tests that Bar does Xyz.</span></div>
<div class="line">TEST_F(DISABLED_BarTest, DoesXyz) { ... }</div>
</div><!-- fragment --><p>{: .callout .note} NOTE: This feature should only be used for temporary pain-relief. You still have to fix the disabled tests at a later date. As a reminder, googletest will print a banner warning you if a test program contains any disabled tests.</p>
<p>{: .callout .tip} TIP: You can easily count the number of disabled tests you have using <code>grep</code>. This number can be used as a metric for improving your test quality.</p>
<h3><a class="anchor" id="autotoc_md65"></a>
Temporarily Enabling Disabled Tests</h3>
<p>To include disabled tests in test execution, just invoke the test program with the <code>--gtest_also_run_disabled_tests</code> flag or set the <code>GTEST_ALSO_RUN_DISABLED_TESTS</code> environment variable to a value other than <code>0</code>. You can combine this with the <code>--gtest_filter</code> flag to further select which disabled tests to run.</p>
<h2><a class="anchor" id="autotoc_md66"></a>
Repeating the Tests</h2>
<p>Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it will fail only 1% of the time, making it rather hard to reproduce the bug under a debugger. This can be a major source of frustration.</p>
<p>The <code>--gtest_repeat</code> flag allows you to repeat all (or selected) test methods in a program many times. Hopefully, a flaky test will eventually fail and give you a chance to debug. Here's how to use it:</p>
<div class="fragment"><div class="line">$ foo_test --gtest_repeat=1000</div>
<div class="line">Repeat foo_test 1000 times and don&#39;t stop at failures.</div>
<div class="line"> </div>
<div class="line">$ foo_test --gtest_repeat=-1</div>
<div class="line">A negative count means repeating forever.</div>
<div class="line"> </div>
<div class="line">$ foo_test --gtest_repeat=1000 --gtest_break_on_failure</div>
<div class="line">Repeat foo_test 1000 times, stopping at the first failure.  This</div>
<div class="line">is especially useful when running under a debugger: when the test</div>
<div class="line">fails, it will drop into the debugger and you can then inspect</div>
<div class="line">variables and stacks.</div>
<div class="line"> </div>
<div class="line">$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.*</div>
<div class="line">Repeat the tests whose name matches the filter 1000 times.</div>
</div><!-- fragment --><p>If your test program contains global set-up/tear-down code, it will be repeated in each iteration as well, as the flakiness may be in it. You can also specify the repeat count by setting the <code>GTEST_REPEAT</code> environment variable.</p>
<h2><a class="anchor" id="autotoc_md67"></a>
Shuffling the Tests</h2>
<p>You can specify the <code>--gtest_shuffle</code> flag (or set the <code>GTEST_SHUFFLE</code> environment variable to <code>1</code>) to run the tests in a program in a random order. This helps to reveal bad dependencies between tests.</p>
<p>By default, googletest uses a random seed calculated from the current time. Therefore you'll get a different order every time. The console output includes the random seed value, such that you can reproduce an order-related test failure later. To specify the random seed explicitly, use the <code>--gtest_random_seed=SEED</code> flag (or set the <code>GTEST_RANDOM_SEED</code> environment variable), where <code>SEED</code> is an integer in the range [0, 99999]. The seed value 0 is special: it tells googletest to do the default behavior of calculating the seed from the current time.</p>
<p>If you combine this with <code>--gtest_repeat=N</code>, googletest will pick a different random seed and re-shuffle the tests in each iteration.</p>
<h2><a class="anchor" id="autotoc_md68"></a>
Distributing Test Functions to Multiple Machines</h2>
<p>If you have more than one machine you can use to run a test program, you might want to run the test functions in parallel and get the result faster. We call this technique <em>sharding</em>, where each machine is called a <em>shard</em>.</p>
<p>GoogleTest is compatible with test sharding. To take advantage of this feature, your test runner (not part of GoogleTest) needs to do the following:</p>
<ol type="1">
<li>Allocate a number of machines (shards) to run the tests.</li>
</ol>
<ol type="1">
<li>On each shard, set the <code>GTEST_TOTAL_SHARDS</code> environment variable to the total number of shards. It must be the same for all shards.</li>
</ol>
<ol type="1">
<li>On each shard, set the <code>GTEST_SHARD_INDEX</code> environment variable to the index of the shard. Different shards must be assigned different indices, which must be in the range <code>[0, GTEST_TOTAL_SHARDS - 1]</code>.</li>
</ol>
<ol type="1">
<li>Run the same test program on all shards. When GoogleTest sees the above two environment variables, it will select a subset of the test functions to run. Across all shards, each test function in the program will be run exactly once.</li>
</ol>
<ol type="1">
<li>Wait for all shards to finish, then collect and report the results.</li>
</ol>
<p>Your project may have tests that were written without GoogleTest and thus don't understand this protocol. In order for your test runner to figure out which test supports sharding, it can set the environment variable <code>GTEST_SHARD_STATUS_FILE</code> to a non-existent file path. If a test program supports sharding, it will create this file to acknowledge that fact; otherwise it will not create it. The actual contents of the file are not important at this time, although we may put some useful information in it in the future.</p>
<p>Here's an example to make it clear. Suppose you have a test program <code>foo_test</code> that contains the following 5 test functions:</p>
<div class="fragment"><div class="line">TEST(A, V)</div>
<div class="line">TEST(A, W)</div>
<div class="line">TEST(B, X)</div>
<div class="line">TEST(B, Y)</div>
<div class="line">TEST(B, Z)</div>
</div><!-- fragment --><p>Suppose you have 3 machines at your disposal. To run the test functions in parallel, you would set <code>GTEST_TOTAL_SHARDS</code> to 3 on all machines, and set <code>GTEST_SHARD_INDEX</code> to 0, 1, and 2 on the machines respectively. Then you would run the same <code>foo_test</code> on each machine.</p>
<p>GoogleTest reserves the right to change how the work is distributed across the shards, but here's one possible scenario:</p>
<ul>
<li>Machine #0 runs <code>A.V</code> and <code>B.X</code>.</li>
<li>Machine #1 runs <code>A.W</code> and <code>B.Y</code>.</li>
<li>Machine #2 runs <code>B.Z</code>.</li>
</ul>
<h2><a class="anchor" id="autotoc_md69"></a>
Controlling Test Output</h2>
<h3><a class="anchor" id="autotoc_md70"></a>
Colored Terminal Output</h3>
<p>googletest can use colors in its terminal output to make it easier to spot the important information:</p>
<pre>...
&lt;font color="green"&gt;[----------]&lt;/font&gt; 1 test from <a class="el" href="class_foo_test.html">FooTest</a>
&lt;font color="green"&gt;[ RUN      ]&lt;/font&gt; FooTest.DoesAbc
&lt;font color="green"&gt;[       OK ]&lt;/font&gt; FooTest.DoesAbc
&lt;font color="green"&gt;[----------]&lt;/font&gt; 2 tests from BarTest
&lt;font color="green"&gt;[ RUN      ]&lt;/font&gt; BarTest.HasXyzProperty
&lt;font color="green"&gt;[       OK ]&lt;/font&gt; BarTest.HasXyzProperty
&lt;font color="green"&gt;[ RUN      ]&lt;/font&gt; BarTest.ReturnsTrueOnSuccess
... some error messages ...
&lt;font color="red"&gt;[   FAILED ]&lt;/font&gt; BarTest.ReturnsTrueOnSuccess
...
&lt;font color="green"&gt;[==========]&lt;/font&gt; 30 tests from 14 test suites ran.
&lt;font color="green"&gt;[   PASSED ]&lt;/font&gt; 28 tests.
&lt;font color="red"&gt;[   FAILED ]&lt;/font&gt; 2 tests, listed below:
&lt;font color="red"&gt;[   FAILED ]&lt;/font&gt; BarTest.ReturnsTrueOnSuccess
&lt;font color="red"&gt;[   FAILED ]&lt;/font&gt; AnotherTest.DoesXyz

 2 FAILED TESTS
</pre><p>You can set the <code>GTEST_COLOR</code> environment variable or the <code>--gtest_color</code> command line flag to <code>yes</code>, <code>no</code>, or <code>auto</code> (the default) to enable colors, disable colors, or let googletest decide. When the value is <code>auto</code>, googletest will use colors if and only if the output goes to a terminal and (on non-Windows platforms) the <code>TERM</code> environment variable is set to <code>xterm</code> or <code>xterm-color</code>.</p>
<h3><a class="anchor" id="autotoc_md71"></a>
Suppressing test passes</h3>
<p>By default, googletest prints 1 line of output for each test, indicating if it passed or failed. To show only test failures, run the test program with <code>--gtest_brief=1</code>, or set the GTEST_BRIEF environment variable to <code>1</code>.</p>
<h3><a class="anchor" id="autotoc_md72"></a>
Suppressing the Elapsed Time</h3>
<p>By default, googletest prints the time it takes to run each test. To disable that, run the test program with the <code>--gtest_print_time=0</code> command line flag, or set the GTEST_PRINT_TIME environment variable to <code>0</code>.</p>
<h3><a class="anchor" id="autotoc_md73"></a>
Suppressing UTF-8 Text Output</h3>
<p>In case of assertion failures, googletest prints expected and actual values of type <code>string</code> both as hex-encoded strings as well as in readable UTF-8 text if they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 text because, for example, you don't have an UTF-8 compatible output medium, run the test program with <code>--gtest_print_utf8=0</code> or set the <code>GTEST_PRINT_UTF8</code> environment variable to <code>0</code>.</p>
<h3><a class="anchor" id="autotoc_md74"></a>
Generating an XML Report</h3>
<p>googletest can emit a detailed XML report to a file in addition to its normal textual output. The report contains the duration of each test, and thus can help you identify slow tests.</p>
<p>To generate the XML report, set the <code>GTEST_OUTPUT</code> environment variable or the <code>--gtest_output</code> flag to the string <code>"xml:path_to_output_file"</code>, which will create the file at the given location. You can also just use the string <code>"xml"</code>, in which case the output can be found in the <code>test_detail.xml</code> file in the current directory.</p>
<p>If you specify a directory (for example, <code>"xml:output/directory/"</code> on Linux or <code>"xml:output\directory\"&lt;/tt&gt; on Windows), googletest will create the XML file in
that directory, named after the test executable (e.g. &lt;tt&gt;foo_test.xml&lt;/tt&gt; for test
program &lt;tt&gt;foo_test&lt;/tt&gt; or &lt;tt&gt;foo_test.exe&lt;/tt&gt;). If the file already exists (perhaps left
over from a previous run), googletest will pick a different name (e.g.
&lt;tt&gt;foo_test_1.xml&lt;/tt&gt;) to avoid overwriting it.

The report is based on the &lt;tt&gt;junitreport&lt;/tt&gt; Ant task. Since that format was
originally intended for Java, a little interpretation is required to make it
apply to googletest tests, as shown here:

@icode{xml} 
&lt;testsuites name="AllTests" ...&gt;
  &lt;testsuite name="test_case_name" ...&gt;
    &lt;testcase    name="test_name" ...&gt;
      &lt;failure message="..."/&gt;
      &lt;failure message="..."/&gt;
      &lt;failure message="..."/&gt;
    &lt;/testcase&gt;
  &lt;/testsuite&gt;
&lt;/testsuites&gt;
@endicode 

*   The root &lt;tt&gt;\&lt;testsuites\&gt;&lt;/tt&gt; element corresponds to the entire test program.
*   &lt;tt&gt;\&lt;testsuite\&gt;&lt;/tt&gt; elements correspond to googletest test suites.
*   &lt;tt&gt;\&lt;testcase\&gt;&lt;/tt&gt; elements correspond to googletest test functions.

For instance, the following program

@icode{c++} 
TEST(MathTest, Addition) { ... }
TEST(MathTest, Subtraction) { ... }
TEST(LogicTest, NonContradiction) { ... }
@endicode 

could generate this report:

@icode{xml} 
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;testsuites tests="3" failures="1" errors="0" time="0.035" timestamp="2011-10-31T18:52:42" name="AllTests"&gt;
  &lt;testsuite name="MathTest" tests="2" failures="1" errors="0" time="0.015"&gt;
    &lt;testcase name="Addition" file="test.cpp" line="1" status="run" time="0.007" classname=""&gt;
      &lt;failure message="Value of: add(1, 1)&amp;#x0A; Actual: 3&amp;#x0A;Expected: 2" type=""&gt;...&lt;/failure&gt;
      &lt;failure message="Value of: add(1, -1)&amp;#x0A; Actual: 1&amp;#x0A;Expected: 0" type=""&gt;...&lt;/failure&gt;
    &lt;/testcase&gt;
    &lt;testcase name="Subtraction" file="test.cpp" line="2" status="run" time="0.005" classname=""&gt;
    &lt;/testcase&gt;
  &lt;/testsuite&gt;
  &lt;testsuite name="LogicTest" tests="1" failures="0" errors="0" time="0.005"&gt;
    &lt;testcase name="NonContradiction" file="test.cpp" line="3" status="run" time="0.005" classname=""&gt;
    &lt;/testcase&gt;
  &lt;/testsuite&gt;
&lt;/testsuites&gt;
@endicode 

Things to note:

*   The &lt;tt&gt;tests&lt;/tt&gt; attribute of a &lt;tt&gt;\&lt;testsuites\&gt;&lt;/tt&gt; or &lt;tt&gt;\&lt;testsuite\&gt;&lt;/tt&gt; element tells how
    many test functions the googletest program or test suite contains, while the
    &lt;tt&gt;failures&lt;/tt&gt; attribute tells how many of them failed.

*   The &lt;tt&gt;time&lt;/tt&gt; attribute expresses the duration of the test, test suite, or
    entire test program in seconds.

*   The &lt;tt&gt;timestamp&lt;/tt&gt; attribute records the local date and time of the test
    execution.

*   The &lt;tt&gt;file&lt;/tt&gt; and &lt;tt&gt;line&lt;/tt&gt; attributes record the source file location, where the
    test was defined.

*   Each &lt;tt&gt;\&lt;failure\&gt;&lt;/tt&gt; element corresponds to a single failed googletest
    assertion.

@subsubsection autotoc_md75 Generating a JSON Report

googletest can also emit a JSON report as an alternative format to XML. To
generate the JSON report, set the &lt;tt&gt;GTEST_OUTPUT&lt;/tt&gt; environment variable or the
&lt;tt&gt;--gtest_output&lt;/tt&gt; flag to the string &lt;tt&gt;"json:path_to_output_file"&lt;/tt&gt;, which will
create the file at the given location. You can also just use the string
&lt;tt&gt;"json"&lt;/tt&gt;, in which case the output can be found in the &lt;tt&gt;test_detail.json&lt;/tt&gt; file
in the current directory.

The report format conforms to the following JSON Schema:

@icode{json} 
{
  "$schema": "<a href="http://json-schema.org/schema#">http://json-schema.org/schema#</a>",
  "type": "object",
  "definitions": {
    "TestCase": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "tests": { "type": "integer" },
        "failures": { "type": "integer" },
        "disabled": { "type": "integer" },
        "time": { "type": "string" },
        "testsuite": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/TestInfo"
          }
        }
      }
    },
    "<a class="el" href="class_test_info.html">TestInfo</a>": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "file": { "type": "string" },
        "line": { "type": "integer" },
        "status": {
          "type": "string",
          "enum": ["RUN", "NOTRUN"]
        },
        "time": { "type": "string" },
        "classname": { "type": "string" },
        "failures": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/Failure"
          }
        }
      }
    },
    "Failure": {
      "type": "object",
      "properties": {
        "failures": { "type": "string" },
        "type": { "type": "string" }
      }
    }
  },
  "properties": {
    "tests": { "type": "integer" },
    "failures": { "type": "integer" },
    "disabled": { "type": "integer" },
    "errors": { "type": "integer" },
    "timestamp": {
      "type": "string",
      "format": "date-time"
    },
    "time": { "type": "string" },
    "name": { "type": "string" },
    "testsuites": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/TestCase"
      }
    }
  }
}
@endicode 

The report uses the format that conforms to the following Proto3 using the
&lt;a href="<a href="https://developers.google.com/protocol-buffers/docs/proto3#json">https://developers.google.com/protocol-buffers/docs/proto3#json</a>" &gt;JSON encoding&lt;/a&gt;:

@icode{proto} 
syntax = "proto3";

package googletest;

import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";

message UnitTest {
  int32 tests = 1;
  int32 failures = 2;
  int32 disabled = 3;
  int32 errors = 4;
  google.protobuf.Timestamp timestamp = 5;
  google.protobuf.Duration time = 6;
  string name = 7;
  repeated TestCase testsuites = 8;
}

message TestCase {
  string name = 1;
  int32 tests = 2;
  int32 failures = 3;
  int32 disabled = 4;
  int32 errors = 5;
  google.protobuf.Duration time = 6;
  repeated TestInfo testsuite = 7;
}

message TestInfo {
  string name = 1;
  string file = 6;
  int32 line = 7;
  enum Status {
    RUN = 0;
    NOTRUN = 1;
  }
  Status status = 2;
  google.protobuf.Duration time = 3;
  string classname = 4;
  message Failure {
    string failures = 1;
    string type = 2;
  }
  repeated Failure failures = 5;
}
@endicode 

For instance, the following program

@icode{c++} 
TEST(MathTest, Addition) { ... }
TEST(MathTest, Subtraction) { ... }
TEST(LogicTest, NonContradiction) { ... }
@endicode 

could generate this report:

@icode{json} 
{
  "tests": 3,
  "failures": 1,
  "errors": 0,
  "time": "0.035s",
  "timestamp": "2011-10-31T18:52:42Z",
  "name": "AllTests",
  "testsuites": [
    {
      "name": "MathTest",
      "tests": 2,
      "failures": 1,
      "errors": 0,
      "time": "0.015s",
      "testsuite": [
        {
          "name": "Addition",
          "file": "test.cpp",
          "line": 1,
          "status": "RUN",
          "time": "0.007s",
          "classname": "",
          "failures": [
            {
              "message": "Value of: add(1, 1)<br  />
 Actual: 3\nExpected: 2",
              "type": ""
            },
            {
              "message": "Value of: add(1, -1)<br  />
 Actual: 1\nExpected: 0",
              "type": ""
            }
          ]
        },
        {
          "name": "Subtraction",
          "file": "test.cpp",
          "line": 2,
          "status": "RUN",
          "time": "0.005s",
          "classname": ""
        }
      ]
    },
    {
      "name": "LogicTest",
      "tests": 1,
      "failures": 0,
      "errors": 0,
      "time": "0.005s",
      "testsuite": [
        {
          "name": "NonContradiction",
          "file": "test.cpp",
          "line": 3,
          "status": "RUN",
          "time": "0.005s",
          "classname": ""
        }
      ]
    }
  ]
}
@endicode 

{: .callout .important}
IMPORTANT: The exact format of the JSON document is subject to change.

@subsection autotoc_md76 Controlling How Failures Are Reported

@subsubsection autotoc_md77 Detecting Test Premature Exit

Google Test implements the &lt;em&gt;premature-exit-file&lt;/em&gt; protocol for test runners to
catch any kind of unexpected exits of test programs. Upon start, Google Test
creates the file which will be automatically deleted after all work has been
finished. Then, the test runner can check if this file exists. In case the file
remains undeleted, the inspected test has exited prematurely.

This feature is enabled only if the &lt;tt&gt;TEST_PREMATURE_EXIT_FILE&lt;/tt&gt; environment
variable has been set.

@subsubsection autotoc_md78 Turning Assertion Failures into Break-Points

When running test programs under a debugger, it's very convenient if the
debugger can catch an assertion failure and automatically drop into interactive
mode. googletest's &lt;em&gt;break-on-failure&lt;/em&gt; mode supports this behavior.

To enable it, set the &lt;tt&gt;GTEST_BREAK_ON_FAILURE&lt;/tt&gt; environment variable to a value
other than &lt;tt&gt;0&lt;/tt&gt;. Alternatively, you can use the &lt;tt&gt;--gtest_break_on_failure&lt;/tt&gt;
command line flag.

@subsubsection autotoc_md79 Disabling Catching Test-Thrown Exceptions

googletest can be used either with or without exceptions enabled. If a test
throws a C++ exception or (on Windows) a structured exception (SEH), by default
googletest catches it, reports it as a test failure, and continues with the next
test method. This maximizes the coverage of a test run. Also, on Windows an
uncaught exception will cause a pop-up window, so catching the exceptions allows
you to run the tests automatically.

When debugging the test failures, however, you may instead want the exceptions
to be handled by the debugger, such that you can examine the call stack when an
exception is thrown. To achieve that, set the &lt;tt&gt;GTEST_CATCH_EXCEPTIONS&lt;/tt&gt;
environment variable to &lt;tt&gt;0&lt;/tt&gt;, or use the &lt;tt&gt;--gtest_catch_exceptions=0&lt;/tt&gt; flag when
running the tests.

@subsection autotoc_md80 Sanitizer Integration

The
&lt;a href="<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html">https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html</a>" &gt;Undefined Behavior Sanitizer&lt;/a&gt;,
&lt;a href="<a href="https://github.com/google/sanitizers/wiki/AddressSanitizer">https://github.com/google/sanitizers/wiki/AddressSanitizer</a>" &gt;Address Sanitizer&lt;/a&gt;,
and
&lt;a href="<a href="https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual">https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual</a>" &gt;Thread Sanitizer&lt;/a&gt;
all provide weak functions that you can override to trigger explicit failures
when they detect sanitizer errors, such as creating a reference from &lt;tt&gt;nullptr&lt;/tt&gt;.
To override these functions, place definitions for them in a source file that
you compile as part of your main binary:

@icode 
extern "C" {
void __ubsan_on_report() {
  FAIL() &lt;&lt; "Encountered an undefined behavior sanitizer error";
}
void __asan_on_error() {
  FAIL() &lt;&lt; "Encountered an address sanitizer error";
}
void __tsan_on_report() {
  FAIL() &lt;&lt; "Encountered a thread sanitizer error";
}
}  // extern "C" </code></p>
<p><code>After compiling your project with one of the sanitizers enabled, if a particular test triggers a sanitizer error, googletest will report that it failed. </code></p>
</div></div><!-- contents -->
</div><!-- PageDoc -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  <ul>
    <li class="footer">Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.13.2 </li>
  </ul>
</div>
</body>
</html>
